Home > Articles > Programming > C/C++

Building Background-Aware Applications for iPhone

  • Print
  • + Share This
This chapter shows how iOS 4 supports background tasks, what types of background tasks are supported, how to suspend applications, and how to execute code in the background.
This chapter is from the book

"The ability to run multiple applications in the background" mocks the Verizon commercial. "Why can't a modern operating system run multiple programs at once?" question the discussion groups. As a developer and a fan of the iPhone, I've found these threads amusing in their naiveté and somewhat confusing. The iPhone has always run multiple applications simultaneously in the background, but they were limited to Apple's applications. This restriction has been to preserve the user experience of the device as a phone. Rather than an "anything goes" approach, Apple has taken steps to ensure that the phone remains responsive at all times.

With the release of iOS 4.x, Apple answers the call from the competition by opening up background processing to third-party applications. Unlike the competitors, however, Apple has been cautious in how it approached backgrounding—opening it up to a specific set of tasks that users commonly encounter. In this hour's lesson, you learn several of the multitasking techniques that you can implement in iOS 4.

Understanding iOS 4 Backgrounding

If you've been working in iOS 4.x or later as you've built the tutorials in this book, you may have noticed that when you quit the applications on your phone or in the iPhone Simulator, they still show up in the iOS task manager, and, unless you manually stop them, they tend to pick up right where they left off. The reason for this is that projects created in iOS 4.x are background-ready as soon as you click the Build and Run button. That doesn't mean that they will run in the background, just that they're aware of the new iOS 4 background features and will take advantage with a little bit of help.

Before we examine how to enable backgrounding (also called multitasking) in our projects, let's first identify exactly what it means to be a background-aware application, starting with the types of backgrounding supported, then the application life cycle methods.

Types of Backgrounding

We explore four primary types of backgrounding in iOS 4.x: application suspension, local notifications, task-specific background processing, and task completion.


When an application is suspended, it will cease executing code but be preserved exactly as the user left it. When the user returns to the application, it appears to have been running the whole time. In reality, all tasks will be stopped, keeping the app from using up your iPhone's resources. Any application that you compile against iOS 4.x will, by default, support background suspension. You should still handle cleanup in the application if it is about to be suspended (see "The Background-Aware Application Life Cycle" section, later in this chapter), but beyond that, it "just works."

In addition to performing cleanup as an application is being suspended, it will be your responsibility to recover from a background suspended state and update anything in the application that should have changed while it was suspended (time/date changes and so on).

Local Notifications

The second type of background processing is the scheduling of local notifications (UILocalNotification). If you've ever experienced a push notification, local notifications are the same but are generated by the applications that you write. An application, while running, can schedule notifications to appear onscreen at a point in time in the future. For example, the following code initializes a notification (UILocationNotification) configures it to appear in five minutes, and then uses the application's scheduleLocalNotification method to complete the scheduling:

UILocalNotification *futureAlert;
futureAlert = [[[UILocalNotification alloc] init] autorelease];
futureAlert.fireDate = [NSDatedateWithTimeIntervalSinceNow:300];
futureAlert.timeZone = [NSTimeZonedefaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:futureAlert];

These notifications, when invoked by iOS, can show a message, play a sound, and even update your application's notification badge. They cannot, however, execute arbitrary application code. In fact, it is likely that you will simply allow iOS to suspend your application after registering your local notifications. A user who receives a notification can click View button in the notification window to return to your application.

Task-Specific Background Processing

Before Apple decided to implement background processing, they did some research on how users worked with their handhelds. What they found was that there were specific types of background processing that people needed. First, they needed audio to continue playing in the background; this is necessary for applications like Pandora. Next, location-aware software needed to update itself in the background so that users continued to receive navigation feedback. Finally, VoIP applications like Skype needed to operate in the background to handle incoming calls.

These three types of tasks are handled uniquely and elegantly in iOS 4.x. By declaring that your application requires one of these types of background processing, you can, in many cases, enable your application to continue running with little alteration. To declare your application capable of supporting any (or all) of these tasks, you will add the Required Background Modes (UIBackgroundModes) key to the project's plist file, and then add values of App Plays Audio (Audio), App Registers for Location Updates (Location), or App Provides Voice over IP Services (VoIP).

Task Completion for Long-Running Tasks

The fourth type of backgrounding that we'll be using in iOS 4.x is task completion. Using task-completion methods, you can "mark" the tasks in your application that will need to finish before it can be safely suspended (file upload/downloads, massive calculations, and so on).

For example, to mark the beginning of a long running task, first declare an identifier for the specific task:

UIBackgroundTaskIdentifier myLongTask;

Then use the application's beginBackgroundTaskWithExpirationHandler method to tell iOS that you're starting a piece of code that can continue to run in the background:

myLongTask = [[UIApplicationsharedApplication]
                  // If you're worried about exceeding 10 minutes, handle it here

And, finally, mark the end of the long-running task with the application endBackgroundTask method:

[[UIApplication sharedApplication] endBackgroundTask:myLongTask];

Each task you mark will have roughly 10 minutes (total) to complete its actions, plenty of time for most common uses. After the time completes, the application is suspended and treated like any other suspended application.

The Background-Aware Application Life Cycle Methods

In Hour 4, "Inside Cocoa Touch," you started learning about the application life cycle, as shown in Figure 21.1. You learned that, in iOS 4.x, applications should clean up after themselves in the applicationDidEnterBackground delegate method. This replaces applicationWillTerminate in earlier versions of the OS, or as you'll learn shortly, in applications that you've specifically marked as not capable (or necessary) to run in the background.

Figure 21.1

Figure 21.1 The iOS 4.x application life cycle.

In addition to applicationDidEnterBackground, there are several other methods that you should implement to be a proper background-aware iOS citizen. For many small applications, you won't need to do anything with these, other than leave them as is in the application delegate. As your projects increase in complexity, however, you'll want to make sure that your apps move cleanly from the foreground to background (and vice versa), avoiding potential data corruption and creating a seamless user experience.

The methods that Apple expects to see in your background-aware apps are as follows:

  • application:didFinishLaunchingWithOptions: Called when your application first launches. If your application is terminated while suspended, or purged from memory, needs to restore its previous state manually. (You did save it your user's preferences, right?)
  • applicationDidBecomeActive: Called when an application launches or returns to the foreground from the background. This method can be used to restart processes and update the user interface, if needed.
  • applicationWillResignActive: Invoked when the application is requested to move to the background or to quit. This method should be used to prepare the application for moving into a background state, if needed.
  • applicationDidEnterBackground: Called when the application has become a background application. This replaces applicationWillTerminate in iOS 4.x. You should handle all final cleanup work in this method. You may also use it to start long-running tasks and use task-completion backgrounding to finish them.
  • applicationWillEnterForeground: Called when an application returns to an active state after being backgrounded.
  • applicationWillTerminate: Invoked when an application on a nonmultitasking version of iOS is asked to quit, or when iOS determines that it needs to shut down an actively running background application.

Method stubs for all of these exist in your iOS 4.x application delegate implementation files. If your application needs additional setup or teardown work, just add the code to the existing methods. As you'll see shortly, many applications, such as the majority of those in this book, require few changes.

Now that you have an understanding of the background-related methods and types of background processing available to you, let's look at how they can be implemented. To do this, we'll reuse tutorials that we've built throughout the book (with one exception). We won't be covering how these tutorials were built, so be sure to refer to the earlier hours if you have questions on the core functionality of the applications.

  • + Share This
  • 🔖 Save To Your Account