繁体   English   中英

如果关闭位置服务,CLLocationManager永远不会更新

[英]If location services is turned off, CLLocationManager never updates

如果用户已关闭位置服务(针对所有应用程序或仅针对我的应用程序),则CLLocationManager永远不会提示并且永远不会更新位置。 这是可以预料的,但有没有办法检测位置服务是否已关闭,并提示重新启用它?

根据文档 ,CLLocationManager有一个静态方法来查看是否启用了LocationServices:

+ (BOOL)locationServicesEnabled

只是为了完成蒂姆的回答。

您始终可以尝试通过CLLocationManager实例上的startUpdatingLocation方法启动位置更新。 如果禁用位置服务,您将通过委托获得有关错误情况的通知,然后您可以打开对话框,要求用户进入“设置”并为您的应用启用位置服务...

#pragma mark - CLLocationManagerDelegate
- (void)locationManager:(CLLocationManager *)inManager didFailWithError:(NSError *)inError{
    if (inError.code ==  kCLErrorDenied) {
        NSLog(@"Location manager denied access - kCLErrorDenied");
        // your code to show UIAlertView telling user to re-enable location services
        // for your app so they can benefit from extra functionality offered by app
    }
}

请注意,您可以通过iOS5上的URL-scheme启动“设置”应用程序(版本低于5.0(且大于5.0),不支持)。 呼叫:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs://"]];

在尝试更新位置之前,您可以检查是否已启用位置服务。

这是我使用的代码片段:

if (TARGET_IPHONE_SIMULATOR) {
    currentLocation = [[CLLocation alloc] initWithLatitude:37.331718 longitude:-122.030629];
    [self methodNameHere:currentLocation];
} else {
    if ([CLLocationManager locationServicesEnabled]) {
        [locationManager startUpdatingLocation];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Location Services Disabled" message:@"Enable location services to do this" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
}

基本上,代码会检查您是否针对模拟器,如果您尝试获取位置,这会给您带来错误,因此我只是硬编码我想要模拟的位置(在本例中为Apple HQ)。 如果定位设备,它会检查是否启用了位置服务,如果是,则调用您要执行的方法,否则会向用户显示警报消息。

我认为更好的方法是做到这一点:

switch ([CLLocationManager authorizationStatus]) {
    case kCLAuthorizationStatusAuthorizedWhenInUse:
    case kCLAuthorizationStatusAuthorizedAlways:
        //we're good to go
        break;
    default:
        //pop up an alert
        break;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM