IOS CLLocation - getting location on ViewDidLoad

This will probably be something simple that I will miss, but I have location services installed (shortened for clarity):

- (void)viewDidLoad { self.locationManager = [[[CLLocationManager alloc] init] autorelease]; self.locationManager.delegate = self; [self.locationManager startUpdatingLocation]; } - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { NSLog(@"%@",newLocation.coordinate.latitude); NSLog(@"%@",newLocation.coordinate.longitude); } 

which works great and gives me a stream of location data to the log.

But I want to be able to instantly get the current location in ViewDidLoad, since I need it only once, and not a constant update - this is only to accurately determine the "nearest" convenience, so that I can inform the user about it, I tried add:

 self.locationLat = [self.locationManager location].coordinate.latitude; self.locationLng = [self.locationManager location].coordinate.longitude; 

in ViewDidLoad right after startUpdatingLocation, but they always exit as null. Is there anything else I need to call to get this data after it starts?

thanks

+4
source share
3 answers

You will get only values

 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 

no other function is available to get location values ​​.. so the fastest way you get values ​​is when this function is called first ...

+2
source
 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { /*report to user*/ [self.locationManager stopUpdatingLocation]; } 

So, you will get the location once, and then stop updating it.

+10
source
 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { [manager stopUpdatingLocation]; NSLog(@"%@",newLocation.coordinate.latitude); NSLog(@"%@",newLocation.coordinate.longitude); } 
+3
source

Source: https://habr.com/ru/post/1399979/


All Articles