【问题标题】:If location services is turned off, CLLocationManager never updates如果位置服务关闭,CLLocationManager 永远不会更新
【发布时间】:2012-01-17 21:11:18
【问题描述】:

如果用户关闭了定位服务(无论是针对所有应用还是只针对我的应用),CLLocationManager 永远不会提示并且永远不会更新位置。这是意料之中的,但有没有办法检测到位置服务已关闭,并提示重新启用它?

【问题讨论】:

    标签: iphone ios core-location


    【解决方案1】:

    根据docs,CLLocationManager有一个静态方法可以查看LocationServices是否开启:

    + (BOOL)locationServicesEnabled
    

    【讨论】:

      【解决方案2】:

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

      您始终可以尝试通过 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://"]];
      

      【讨论】:

      【解决方案3】:

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

      这是我使用的代码的 sn-p:

      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) .如果以设备为目标,它会检查是否启用了定位服务,如果是,它会调用您要执行的方法,如果没有,它会向用户显示一条警报消息。

      【讨论】:

        【解决方案4】:

        我认为解决这个问题的更好方法是这样做:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-03-30
          • 2012-02-16
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多