iOS 8 requires that you call either CLLocationManager.requestWhenInUseAuthorization or CLLocationManager.requestAlwaysAuthorization before you call CLLocationManager.startUpdatingLocation
.
@interface MyViewController : UIViewController <CLLocationManagerDelegate>
@property CLLocationManager *locationManager;
@end
requestWhenInUseAuthorization
and requestAlwaysAuthorization
run asynchronously so you want to make sure that your CLLocationManager object isn't cleaned-up before the use can respond to the alert.
- (void) viewDidAppear:(BOOL)animated {
if ([CLLocationManager locationServicesEnabled]) {
self.locationManager = [CLLocationManager new];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
SEL selector = NSSelectorFromString(@"requestWhenInUseAuthorization");
if ([self.locationManager respondsToSelector:selector]) {
[self.locationManager requestWhenInUseAuthorization];
} else {
[self.locationManager startUpdatingLocation];
}
} else {
...
}
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
[self.locationManager startUpdatingLocation];
} else if (status == kCLAuthorizationStatusAuthorized) {
// iOS 7 will redundantly call this line.
[self.locationManager startUpdatingLocation];
} else if (status > kCLAuthorizationStatusNotDetermined) {
...
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
...
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
...
}
When you implement CLLocationManagerDelegate
you now need to implement the locationManager:didChangeAuthorizationStatus: method as well. Within this method you can check if the user has given the app permission or not, and act accordingly.
If [CLLocationManager authorizationStatus] = nil
then locationManager:didChangeAuthorizationStatus:
will be called when the authorizationStatus is set to kCLAuthorizationStatusNotDetermined
and again when the user make their selection from the alert dialog.