locationServicesEnabled 测试在 viewDidLoad 中被禁用时通过

Posted

技术标签:

【中文标题】locationServicesEnabled 测试在 viewDidLoad 中被禁用时通过【英文标题】:locationServicesEnabled test passes when they are disabled in viewDidLoad 【发布时间】:2010-08-04 00:29:16 【问题描述】:

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

if([CLLocationManager locationServicesEnabled]) 
   //Do something now

由于某种原因,此测试总是通过。如果我尝试访问位置服务,我会收到位置管理器的 kCLErrorDenied 错误。什么给了?

我是否使用了错误的测试?

【问题讨论】:

【参考方案1】:

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];

有关更多选项,请参阅CLLocationManager class reference 中有关 CLError 常量的文档。

【讨论】:

这是有道理的,为什么它总是返回 true。谢谢! @Dan,如果 locationServicesEnabled 为 false,那么我已经等了很长时间,但是没有调用委托 (locationManager:didFailWithError:) 方法。是什么原因??【参考方案2】:

ios 4.2 现在允许通过 CLLocationManager +authorizationStatus 方法确定位置服务是否被拒绝。

【讨论】:

以上是关于locationServicesEnabled 测试在 viewDidLoad 中被禁用时通过的主要内容,如果未能解决你的问题,请参考以下文章

CLLocationManager locationServicesEnabled 开启但个别关闭

locationServicesEnabled 测试在 viewDidLoad 中被禁用时通过

检查 locationServicesEnabled 始终返回 YES,无论手动拨动开关决定是不是启用了位置服务

Map定位

检查 iOS 定位服务

ios 打开app应用权限