I'm looking for a way to get a background location update every n minutes in my iOS application. I'm using iOS 4.3 and the solution should work for non-jailbroken iPhones.
I tried / considered following options:
CLLocationManager startUpdatingLocation/startMonitoringSignificantLocationChanges
: This works in the background as expected, based on the configured properties, but it seems not possible to force it to update the location every n minutesNSTimer
: Does work when the app is running in the foreground but doesn't seem to be designed for background tasks- Local notifications: Local notifications can be scheduled every n minutes, but it's not possible to execute some code to get the current location (without the user having to launch the app via the notification). This approach also doesn't seem to be a clean approach as this is not what notifications should be used for.
UIApplication:beginBackgroundTaskWithExpirationHandler
: As far as I understand, this should be used to finish some work in the background (also limited in time) when an app is moved to the background rather than implementing "long-running" background processes.
How can I implement these regular background location updates?
On iOS 8/9/10 to make background location update every 5 minutes do the following:
Go to Project -> Capabilities -> Background Modes -> select Location updates
Go to Project -> Info -> add a key NSLocationAlwaysUsageDescription with empty value (or optionally any text)
To make location working when your app is in the background and send coordinates to web service or do anything with them every 5 minutes implement it like in the code below.
I'm not using any background tasks or timers. I've tested this code with my device with iOS 8.1 which was lying on my desk for few hours with my app running in the background. Device was locked and the code was running properly all the time.
This is needed for background location tracking since iOS 9.
Attached is a Swift solution based in:
Define
App registers for location updates
in the info.plistKeep the locationManager running all the time
Switch
kCLLocationAccuracy
betweenBestForNavigation
(for 5 secs to get the location) andThreeKilometers
for the rest of the wait period to avoid battery drainageThis example updates location every 1 min in Foreground and every 15 mins in Background.
The example works fine with Xcode 6 Beta 6, running in a iOS 7 device.
In the App Delegate (mapView is an Optional pointing to the mapView Controller)
In the mapView (locationManager points to the object in the AppDelegate)