Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS CLLocation - getting the location on ViewDidLoad

Tags:

ios

This is probably going to be something simple I'm missing, but I have the location services set up as so (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 fine and gives me a stream of location data to the log.

But what I want is to be able to get the current location immediately in the ViewDidLoad, as I only need it once, not a constant update - it's only to pinpoint a "nearest" amenity so I can report back to the user. I've tried adding:

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

to the ViewDidLoad immediately after startUpdatingLocation, but they always come out as null. Is there something else I have to call to get that data once it's running?

Thanks

like image 438
Dave Avatar asked Dec 07 '22 15:12

Dave


1 Answers

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

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

like image 55
Roman Temchenko Avatar answered Jan 09 '23 11:01

Roman Temchenko