wjans wjans - 1 year ago 92
Objective-C Question

How do I get a background location update every n minutes in my iOS application?

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 minutes

  • NSTimer
    : 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?

Answer Source

Found a solution to implement this with the help of the Apple Developer Forums. I did the following:

  • Specify location background mode
  • Use an NSTimer in the background by using UIApplication:beginBackgroundTaskWithExpirationHandler:
  • In case n is smaller than UIApplication:backgroundTimeRemaining ,it will work just fine, in case n is larger, the location manager should be enabled (and disabled) again before there is no time remaining to avoid the background task being killed.

This does work since location is one of the three allowed types of background execution.

Note: Did loose some time by testing this in the simulator where it doesn't work, works fine on my phone.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download