Pheepster
Pheepster

Reputation: 6347

Getting a single location update using CLLocationManager

I have a unique requirement to provide a device location. It's unique because I need to turn on location updates, grab the device location, then immediately turn off updates (for battery life requirements). Since it may take some time to get the location, I have some concerns about the following code sample...

-(CLLocation *)getActualLocation{
    CLLocation *actualLocation;
    [coreLocationManager startUpdatingLocation];
    actualLocation = [coreLocationManager location];

    // stop updates

    return actualLocation;
}

...since the call to set actualLocation will likely be executed before any updates will be available. Any suggesions on how to go about this? Thanks!

Upvotes: 0

Views: 743

Answers (3)

Marchy
Marchy

Reputation: 3714

As of iOS9 you can call the new requestLocation() method which does what you described, ensuring only one callback before turning the location off

Official docs: https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManager_Class/#//apple_ref/occ/instm/CLLocationManager/requestLocation

Blog post: http://szulctomasz.com/ios-9-getting-single-location-update-with-requestlocation/

Upvotes: 1

davbryn
davbryn

Reputation: 7176

Let it delegate to you

This will always need to be an asynchronous operation, so you will have to enable updates and wait until you get feedback. Once it comes in you can stop location manager from updating

Upvotes: 0

Cornelius
Cornelius

Reputation: 4264

Your best option imho is to wait for the first location update to be delivered and then immediately stop the location updater. This can still leave you with an outdated or very inaccurate position, but you can check those in the delegate if necessary.

Directly fetching the location after you started updating will probably not get you good results, as the update is done async and results won't be available yet.

iOS is already doing a good job in reducing power consumption during location updates, so this should not be such a big deal.

Upvotes: 1

Related Questions