第一次没有调用 didUpdateLocations 运行

didUpdateLocation not called first time run

我的应用程序中的位置服务在您第一次使用时无法使用 运行。第二次,以及之后的任何时候,它都工作正常。这是我的代码:

- (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);
}

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

来自Apple docs

When the current authorization status is kCLAuthorizationStatusNotDetermined, this method runs asynchronously and prompts the user to grant permission to the app to use location services