didUpdateLocation未在首次运行时调用

Kev*_*ath 1 iphone cllocation ios

我的应用中的定位服务在您首次运行时无法正常工作。第二次以及之后的任何时间,它都可以正常工作。这是我的代码:

- (void)viewDidLoad {
[super viewDidLoad];

locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManager.distanceFilter = kCLDistanceFilterNone;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.allowsBackgroundLocationUpdates = true;
[locationManager requestAlwaysAuthorization];

if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways ||
    [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse) {
    [locationManager startUpdatingLocation];
}
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
latitude = locationManager.location.coordinate.latitude;
longitude = locationManager.location.coordinate.longitude;
NSLog(@"New Location. Lat: %f, Long: %f", latitude, longitude);
}
Run Code Online (Sandbox Code Playgroud)

ama*_*111 5

问题是requestAlwaysAuthorization异步运行,因此检查授权和调用的代码startUpdatingLocation将在用户授予授权之前执行。这就是为什么第二次可以使用的原因,因为他们是第一次给予许可。您可以做的是locationManager:didChangeAuthorizationStatus:在委托上实施并startUpdatingLocation在其中调用(如果状态更改为授权)。

苹果文档

当前授权状态为kCLAuthorizationStatusNotDetermined时,此方法异步运行,并提示用户向应用授予使用位置服务的权限