使用MapKit和CoreLocation时出现Xcode警告

nar*_*ner 1 cocoa-touch objective-c core-location mkmapview ios

我正在尝试使用实现一个实例MKMapView,用于CoreLocation跟踪用户位置,然后放大它们的位置.

我只想在我处于前台时跟踪用户的位置.由于我的应用程序是针对iOS8的,因此我有一个密钥的plist条目NSLocationWhenInUseUsageDescription.

当我第一次运行应用程序时,应用程序会相应地询问它是否可以访问我的位置.单击"允许"后,我会从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];
}
Run Code Online (Sandbox Code Playgroud)

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

mat*_*att 5

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

只需看看以下文档requestWhenInUseAuthorization:

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

懂吗?以异步方式运行.这意味着请求权限发生在另一个线程的后台.

文档继续说:

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

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

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

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

  • 检查状态.

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

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

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