How do you determine with CLLocationManager when a user denies access to location services?

∥☆過路亽.° 提交于 2019-12-08 07:09:27
testing

Taken from this SO answer: locationServicesEnabled test passes when they are disabled in viewDidLoad

The locationServicesEnabled class method only tests the global setting for Location Services. AFAIK, there's no way to test if your app has explicitly been denied. You'll have to wait for the location request to fail and use the CLLocationManagerDelegate method locationManager:didFailWithError: to do whatever you need. E.g.

- (void)locationManager: (CLLocationManager *)manager
       didFailWithError: (NSError *)error {

    NSString *errorString;
    [manager stopUpdatingLocation];
    NSLog(@"Error: %@",[error localizedDescription]);
    switch([error code]) {
        case kCLErrorDenied:
            //Access denied by user
            errorString = @"Access to Location Services denied by user";
            //Do something...
            break;
        case kCLErrorLocationUnknown:
            //Probably temporary...
            errorString = @"Location data unavailable";
            //Do something else...
            break;
        default:
            errorString = @"An unknown error has occurred";
            break;
        }
    }

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:errorString delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
    [alert show];
    [alert release];
}

See the documentation on the CLError constants in the CLLocationManager class reference for more options.

Brennan

I answered my own question in the comment to the question above.

The answer (copied from the comment above):

It appears that you must wait for locationManager:didFailWithError: to be called and the error code will point to values in CLError.h. Values are kCLErrorLocationUnknown, kCLErrorDenied, kCLErrorNetwork, and kCLErrorHeadingFailure. It appears that the second value is what I should check to see if the user denied access to location services.

Since iOS 4.2, you can use the global method + (CLAuthorizationStatus)authorizationStatus from CLLocationManager :

if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
    //User denied access to location service for this app
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!