如果之前禁用了位置服务,CLLocationManager 不会显示弹出窗口

CLLocationManager doesn't show popup if location services were previously disabled

当我启动我的应用程序时,我会像这样检查当前的位置授权状态:

- (void)checkCurrentStatus
{
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined)
{
   [self.locationManager requestWhenInUseAuthorization];
}
else
if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied && ![CLLocationManager locationServicesEnabled])
{
    [self.locationManager startUpdatingLocation];
}
}

如果(针对整个设备)启用了整体定位服务,而不是仅请求用户许可,则会弹出警报。如果它们被禁用(else if 条件),那么我需要调用 startUpdatingLocation,因为当授权状态为 kCLAuthorizationStatusDenied(没有任何 if 条件)时,调用 [self.locationManager requestWhenInUseAuthorization]; 无效。好的,所以我调用 startUpdatingLocation,然后弹出警报:

Turn On Location Services to Allow "AppName" to Determine Your Location

好的,我去设置里打开整体定位服务。在那之后 authorizationStatus 变成 kCLAuthorizationStatusNotDetermined 但是当我调用 requestWhenInUseAuthorization 它没有效果!没有弹出窗口出现,没有提示用户授权位置,状态保持不变,我无法使用位置管理器。我该如何处理?

来自 Apple 关于 CLLocationManager 的文档 - (void)requestWhenInUseAuthorization

If the current authorization status is anything other than kCLAuthorizationStatusNotDetermined, this method does nothing and does not call the locationManager:didChangeAuthorizationStatus: method

这是您需要的:

- (void)requestAlwaysAuthorization
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

    // If the status is denied or only granted for when in use, display an alert
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusDenied) {
        NSString *title;
        title = (status == kCLAuthorizationStatusDenied) ? @"Location services are off" : @"Background location is not enabled";
        NSString *message = @"To use background location you must turn on 'Always' in the Location Services Settings";

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                            message:message
                                                           delegate:self
                                                  cancelButtonTitle:@"Cancel"
                                                  otherButtonTitles:@"Settings", nil];
        [alertView show];
    }
    // The user has not enabled any location services. Request background authorization.
    else if (status == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestAlwaysAuthorization];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        // Send the user to the Settings for this app
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:settingsURL];
    }
}

Courtesy copy of this blog post