Location Services in the Background

suggest change

To use standard location services while the application is in the background, first turn on Background Modes in the Capabilities tab of the target settings, and select Location updates.

#TODO: missing image, was http://cdn2.raywenderlich.com/wp-content/uploads/2014/12/background_modes.png

Or, add it directly to the Info.plist.

<key>NSLocationAlwaysUsageDescription</key>
<string>I want to get your location information in the background</string>

<key>UIBackgroundModes</key>
<array>
    <string>location</string>
</array>

On iOS 11 and later, requestAlwaysAuthorization also needs NSLocationWhenInUseUsageDescription and NSLocationAlwaysAndWhenInUseUsageDescription. The plist above is the iOS 8 form.

Then set up the location manager. Keep a strong reference to it, or updates stop. Import CoreLocation, and conform to CLLocationManagerDelegate. The Swift sample below uses self.locationManager without creating it.

Objective C

//The Location Manager must have a strong reference to it.
_locationManager = [[CLLocationManager alloc] init];
_locationManager.delegate = self;
//Request Always authorization (iOS8+)
if ([_locationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
    [_locationManager requestAlwaysAuthorization];
}

//Allow location updates in the background (iOS9+)
if ([_locationManager respondsToSelector:@selector(allowsBackgroundLocationUpdates)]) {
    _locationManager.allowsBackgroundLocationUpdates = YES;
}

[_locationManager startUpdatingLocation];

Swift

self.locationManager.delegate = self

if #available (iOS 8.0,*) {
    self.locationManager.requestAlwaysAuthorization()
}

if #available (iOS 9.0,*) {
    self.locationManager.allowsBackgroundLocationUpdates = true
}

self.locationManager.startUpdatingLocation()

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents