Guides
Guides

iOS: Location Updates

A guide to location updates on iOS

iOS location updates are provided through the CoreLocation library. This can provide location updates to your app when it is running in the foreground, the background and when terminated.

You will need to create a location services class that contains an instance of the CLLocationManager class. The CLLocationManager instance should be instantiated and registered for the required level of location updates every time the app is run. Once the app has been registered for location updates they will be provided through the CLLocationManagerDelegate you specify.

📘

Note

Location updates provided when your app is terminated will launch your app in the background, calling the application willFinishLaunchingWithOptions: and didFinishLaunchingWithOptions: methods. To properly handle the location you must ensure the location manager is created and registered for updates during this launch.

// location services should implement location manager delegate
@interface LocationServices () <CLLocationManagerDelegate>

@property (strong, nonatomic) CLLocationManager *locationManager;

// Setup location manager
- (void)setupLocationManager {
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
}
class LocationManager: NSObject, CLLocationManagerDelegate {
 
    var locationManager: CLLocationManager!
    
    // setup location manager
    func setupLocationManager() {
        locationManager = CLLocationManager()
        locationManager.delegate = self
    }
}

Registering for updates

Apple provides a guide to choosing your authorization level and registering for the appropriate location updates here.

📘

Note

Make sure that you have added all the correct information to your app's info.plist to support location updates, like the NSUsageLocationDescriptions that are used to explain why you need locations to the user. If you want locations in the background you will also need to check the location updates box in the background modes capabilities for your app.

Passing location updates to Marigold

Once you have registered and your app is receiving location updates they will arrive through the CLLocationManagerDelegate methods. You can then pass the location using the updateLocation: method.

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    CLLocation *location = [locations lastObject];
    [[Marigold new] updateLocation:location];
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations.last
    Marigold().updateLocation(location)
}

Background locations

In order to receive background locations you will need to add some additional capabilities to your app. Apple provides a guide for this here. Most users are reluctant to allow apps to track them all the time so this option should be implemented carefully.