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.
stopUpdatingLocation
?I found this similar question IOS didUpdateLocations. But does NSTimer
the proper way to go, it seems clunky.
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]];
}