[Solved] Why is this code updating location twice every time?


After a quick look at Apple’s documentations, I’ve noticed that the delegate method you are using, - locationManager:didUpdateToLocation:fromLocation: is deprecated since iOS 6.
Instead, you should use - locationManager:didUpdateLocations:.

Try replacing your code with the code below and see if it make any difference:

EDIT- I’ve edit the code below to handle the double-call you get.
From your post above I see they are almost simultaneously, So basically we’ll check if at least 1 seconds has passed since last call.
There are probably better ways to do it, but that was just at the top of my head…
Haven’t checked it in Xcode, but, if I haven’t made a typo or something, it should work.

// ViewController.m  
@interface ViewController ()  
@property (nonatomic, strong) NSDate *lastUpdateTime;  // Create a property  
@end                                                   // to hold current time  

- (void)viewDidLoad {  
    [super viewDidLoad];  
    self.lastUpdateTime = [NSDate date];  // In viewDidLoad, 'initialize' it  
                                          // to get the current time  
}  

- (void)locationManager:(CLLocationManager *)manager
 didUpdateLocations:(NSArray *)locations  
{  
    NSTimeInterval passedTime = -[self.lastUpdateTime timeIntervalSinceNow];  
    // Here we are checking how much seconds have passed since our lastUpdateTime  
    // Since lastUpdateTime is in the past, the result will be negative, therefore  
    // the minus sign, so we'll get a positive number  

    if(passedTime < 1) {  
        return;  
    }  // Now we check if less than one second have passed. If so, the whole method  
       // will return. If not, it will just continue executing

    CLLocation *currentLocation = [locations lastObject];  
    self.lastUpdateTime = [NSDate date];  // Don't forget to update the lastUpdateTime  
                                          // To hold the new update time

    if (currentLocation != nil) {  
        NSLog(@"Location updated: %@", currentLocation);
        _LatitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];  
        _LongitudeLabel.text = [NSString stringWithFormat:@"%.6f", currentLocation.coordinate.longitude];  
        _GPSAccuracyLabel.text = [NSString stringWithFormat:@"%.2f", currentLocation.horizontalAccuracy];  
        _AltitudeLabel.text = [NSString stringWithFormat:@"%.2f", currentLocation.altitude];  
        _VerticalAccuracyLabel.text = [NSString stringWithFormat:@"%.2f", currentLocation.verticalAccuracy];  
    }  
}

7

solved Why is this code updating location twice every time?