使用MapKit和CoreLocation时出现Xcode警告

时间:2015-05-28 00:27:51

标签: ios objective-c cocoa-touch mkmapview core-location

我尝试使用实现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];
}

有没有人知道为什么会发生这种警告?

1 个答案:

答案 0 :(得分:5)

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

只需查看requestWhenInUseAuthorization上的文档:

  

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

得到那个? 异步运行。这意味着请求权限发生在另一个线程的后台。

文档继续说:

  

确定状态后,位置管理员将结果传递给代理人的locationManager:didChangeAuthorizationStatus:方法

所以,实现那个方法。如果您刚获得许可,那么 就是您可以开始使用位置管理器的信号。

此外,您错过了一个重要的步骤:您不是检查实际的状态。如果状态未确定,您应该只是要求授权。如果状态受到限制或被拒绝,则您根本不能使用位置管理器;如果状态被授予,则无需再次请求授权。

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

  • 检查状态。

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

  • 状态是否已授予?继续获取位置更新或在地图上进行位置。

  • 状态是否未确定?请求授权并停止。将locationManager:didChangeAuthorizationStatus:视为授权请求的完成处理程序。那时,回到流程图的开头!