BlackM
BlackM

Reputation: 4065

Get coordinates once with CLLocation manager in iOS

I am using this code to get coordinates:

_locationManager = [[CLLocationManager alloc] init];
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.delegate = self;
[_locationManager startUpdatingLocation];

and then I am using the

- (void)locationManager:(CLLocationManager *)manager
 didUpdateLocations:(NSArray *)locations
{

_currentLocation = [locations lastObject];


//Doing some stuff

//I am using stopUpdatingLocation but this delegate is called a lot of times
[_locationManager stopUpdatingLocation];



 }

I actually want to get once the coordinates because I want to avoid executing the code in the didUpdateLocation more than once. How can I do that?

Upvotes: 1

Views: 395

Answers (1)

Rowan Freeman
Rowan Freeman

Reputation: 16378

This occurs because the location manager fires its updates many times, progressively getting more accurate location results.

One way to stop this is simply to use a boolean

BOOL _hasUpdatedUserLocation = NO;

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    if (!_hasUpdatedUserLocation) {
        _hasUpdatedUserLocation = YES;
        ... // other code
    }
}

Alternatively, you could kill the delegate:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    [locationManager setDelegate:nil];
    ... // other code
}

Upvotes: 0

Related Questions