Search code examples
iosobjective-cgeolocationcllocationmanagercllocation

iOS - CLLocation Manager didUpdateLocations called too much time


I am refactoring old code in order to get things clean, especially the geolocation part, which is kind of messy right now.

I am logging every geolocation methods and I found out that the didUpdateLocations is called too much time.

Here is some code from my Splashscreen:

- (void)viewDidLoad
{
    [super viewDidLoad];

    _locationManager = [[CLLocationManager alloc] init];
    _locationManager.delegate = self;
    [self startLocationRetrieval];
}

Here is the startLocationRetrieval method

   -(void) startLocationRetrieval
    {
        if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)])
            [_locationManager requestWhenInUseAuthorization];
        if ([CLLocationManager locationServicesEnabled]) {
            _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
            [_locationManager startUpdatingLocation];
        }else {
            _isDataLoaded = YES;
            [self loadHomeView];
        }

Here are the CLLocation delegate methods

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    DDLogError(@"GEOLOC CLLocationManager didFailWithError: %@", error);
    [self loadHomeView];
}

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations
{
    DDLogInfo(@"GEOLOC Splashscreen didUpdateLocations -> %@", locations);
    [self manageNewLocation:[locations lastObject]];
}

And my method to handle location changes

-(void) manageNewLocation:(CLLocation *)location
{
    _coordinate = location;
    DDLogDebug(@"GEOLOC Splash manageNewLocation = %@", _coordinate);
   [self loadHomeView];
}

The loadHomeView method is simply to trigger the performSegueWithIdentifier in order to go to the HomePage.

  • Do you think this is a good implementation or can it be cleaner ?
  • Where should I stopUpdatingLocation ?

I found this similar question IOS didUpdateLocations. But does NSTimer the proper way to go, it seems clunky.


Solution

  • once location is fetched you need to stop the update location using [manager stopUpdatingLocation];

      - (void)locationManager:(CLLocationManager *)manager
         didUpdateLocations:(NSArray *)locations
    {
           [manager stopUpdatingLocation];
           manager = nil;
        DDLogInfo(@"GEOLOC Splashscreen didUpdateLocations -> %@", locations);
        [self manageNewLocation:[locations lastObject]];
    }