简体   繁体   中英

iOS Location Services - App is checking for location before allowed

Just trying to determine a user's location. Here's the code:

self.locationManager = [[CLLocationManager alloc] init];
//self.locationManager.delegate = self;
self.locationManager.distanceFilter = 80.0;
[self.locationManager startUpdatingLocation];

self.geoCoder = [[CLGeocoder alloc] init];
[self.geoCoder reverseGeocodeLocation: self.locationManager.location completionHandler:

 ^(NSArray *placemarks, NSError *error) {

     CLPlacemark *placemark = [placemarks objectAtIndex:0];

     UIAlertView *locationAlert = [[UIAlertView alloc] initWithTitle:@"Location" message:[NSString stringWithFormat:@"The app has determined that your country is: %@ (%@)", placemark.country, placemark.ISOcountryCode] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
     [alert show];


 }];

The first time I run the app, I get a double alert popup. The locationAlert pops up first, informing the user of a (null) country, then the default popup that says the app would like to use my location pops up pretty much simultaneously. If I click YES, the next time I run the app I will get the single popup of the user's correct country.

So my question is, how can I first gain permission to access the user's location, THEN run this code to find their location, without getting a null response because I've queried their location without permission?

The reverse geolocation code is trying to use the location property from the locationManager but it is not valid until the CLLocationManager delegate method locationManager:didUpdateToLocation:fromLocation: is called.

You should have a delegate method like this one to handle location updates.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM