location services within my app are not working the first time you run it. The second time, and any time after that though, it works fine. Here's my code:
- (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);
}
The issue is that requestAlwaysAuthorization
runs asynchronously, so your code which checks authorization and calls startUpdatingLocation
will execute before authorization has been given by the user. That's why it'll work the second time, because they gave the permission the first time. What you can do is implement locationManager:didChangeAuthorizationStatus:
on the delegate and call startUpdatingLocation
in there too (if status changed to authorized).
From 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