locationServicesEnabled测试在viewDidLoad中被禁用时传递

Ada*_*dam 8 iphone cllocationmanager

我在设置面板中为我的应用程序禁用了位置服务.我在视图控制器中的viewDidLoad中运行测试,看看它们是否已启用:

if([CLLocationManager locationServicesEnabled]) {
   //Do something now
}
Run Code Online (Sandbox Code Playgroud)

此测试总是因某种原因而通过.如果我尝试访问位置服务,我会得到位置管理器的kCLErrorDenied错误.是什么赋予了?

我使用了错误的测试吗?

小智 25

locationServicesEnabled类方法只测试了位置服务的全局设置.AFAIK,没有办法测试你的应用是否被明确拒绝.您将不得不等待位置请求失败并使用CLLocationManagerDelegate方法locationManager:didFailWithError:来执行您需要的任何操作.例如:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

有关更多选项,请参阅CLLocationManager类参考中有关CLError常量的文档.


GBe*_*gen 20

iOS 4.2现在允许通过CLLocationManager +authorizationStatus方法确定是否已拒绝位置服务.