14.5. Handling Location Changes in the Background

Problem

You are writing an application whose main functionality is processing location changes, using Core Location. You want the application to retrieve the iOS device location changes even if the application is sent to the background.

Solution

Add the location value to the UIBackgroundModes key of your main application .plist file, like so:

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

Discussion

When your application is running in the foreground, you can receive delegate messages from an instance of CLLocationManager telling you when iOS detects that the device is at a new location. However, if your application is sent to the background and is no longer active, the location delegate messages will not be delivered normally to your application. They will instead be delivered in a batch when your application again becomes the foreground application.

If you still want to be able to receive changes in the location of the user’s device while running in the background, you must add the location value to the UIBackgroundModes key of your application’s main .plist file, as shown in this recipe’s Solution. Once in the background, your application will continue to receive the changes in the device’s location. Let’s test this in a simple app with just the app delegate.

What I intend to do in this app is to keep a boolean value in the app delegate, called executingInBackground. When ...

Get iOS 6 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.