Search code examples
ioscore-locationcllocationmanagerregion

iOS 7.1 CoreLocation and geofencing when app is closed


I am currently using CoreLocation to set up geofences and need the app to store events in a database whenever the user enters or exits a geofence. It works when the app is running or in the background, but I need it to somehow execute the database saving code of the app even when the app is terminated (i.e. closed by swiping up on the multitasking menu).

I am using iOS 7.1 which I thought automatically did this, but it is not working for me. How can I get this to work? I am using the startMonitoringForRegion method in the CLLocationManager class to monitor the regions. Is there something extra I need to do so that the app will be notified in the background? Also, where would the database saving code go in the app for when the app is restarted (currently it is in the didFinishLoadingWithOptions menu of the app delegate).


Solution

  • I'm not sure about iOS7, but as of iOS8, according to Apple Docs:

    The region monitoring service delivers events normally while an app is running in the foreground or background. (You can use this service for both geographic and beacon regions.) For a terminated iOS app, this service relaunches the app to deliver events. Use of this service requires “Always” authorization from the user.

    That means geofence will work even when the app is terminated. Also, the callback is in appDidFinishLaunching, where you get the info dictionary in the key UIApplicationLaunchOptionsLocationKey

    In iOS, the regions you register with the location manager persist between launches of your application. If a region crossing occurs while your iOS app is not running, the system automatically wakes it up (or relaunches it) in the background so that it can process the event. When relaunched, all of the regions you configured previously are made available in the monitoredRegions property of any location manager objects you create.