使用MapKit和CoreLocation时的Xcode警告

我试图使用实现MKMapView的实例,使用CoreLocation跟踪用户的位置,然后放大到他们在哪里。

我只想跟踪用户的位置,当我在前台。 由于我的应用程序是针对iOS8,我有一个关键的NSLocationWhenInUseUsageDescription plist入口。

当我第一次运行应用程序时,应用程序会正确地询问是否可以访问我的位置。 当我点击“允许”后,我收到来自Xcode的以下警告:

Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.

…这有点令人困惑,因为我实际上正在调用requestWhenInUseAuthorization ,在我的代码中可以看到:

 @property (strong, nonatomic) IBOutlet MKMapView *mapView; @property(nonatomic, retain) CLLocationManager *locationManager; @end @implementation MapView - (void)viewDidLoad { [super viewDidLoad]; [self locationManager]; [self updateLocation]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; self.locationManager = nil; } - (CLLocationManager *)locationManager { //We only want to get the location when the app is in the foreground [_locationManager requestWhenInUseAuthorization]; if (!_locationManager) { _locationManager = [[CLLocationManager alloc] init]; _locationManager.desiredAccuracy = kCLLocationAccuracyBest; } return _locationManager; } - (void)updateLocation { _mapView.userTrackingMode = YES; [self.locationManager startUpdatingLocation]; } 

有没有人有任何洞察,为什么会发生这个警告?

你正在调用requestWhenInUseAuthorization ,那是真的。 但是你是否在等待,直到你获得授权? 不,你不是。 您(作为用户)正在点击“允许”,但这已经太晚了:您的代码已经继续,直接告诉地图视图开始跟踪用户的位置。

只要看看requestWhenInUseAuthorization的文档,当使用requestWhenInUseAuthorization

当前授权状态为kCLAuthorizationStatusNotDetermined时,此方法asynchronous运行

懂吗? 运行asynchronous 。 这意味着要求权限发生在另一个线程的后台。

文件继续说:

状态确定后,位置pipe理器将结果传递给委托的locationManager:didChangeAuthorizationStatus:方法

所以,实施该方法。 如果您刚获得许可,那么您可以开始使用位置pipe理器的信号。

而且,你错过了一个重要的步骤:你没有检查实际的状态。 如果状态不确定,您应该只是要求授权。 如果地位受到限制或被拒绝,则根本不能使用地点经理; 如果状态被授予,则再次要求授权是没有意义的。

所以,总而言之,你的逻辑stream程图应该是:

  • 检查状态。

  • 状态是限制还是拒绝? 停止。 您无法使用获取位置更新或在地图上进行位置。

  • 是否授予了地位? 继续获取位置更新或在地图上执行位置。

  • 地位未定吗? 请求授权并停止。 将locationManager:didChangeAuthorizationStatus:作为授权请求的完成处理程序。 在这一点上,回到stream程图的开始!