Dave
Dave

Reputation: 493

iOS CLLocation - getting the location on ViewDidLoad

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

Upvotes: 4

Views: 5653

Answers (3)

user1583304
user1583304

Reputation: 31

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

Upvotes: 3

Shubhank
Shubhank

Reputation: 21805

You will only get the values in

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

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

Upvotes: 2

Roman Temchenko
Roman Temchenko

Reputation: 1806

- (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.

Upvotes: 10

Related Questions