An Overview of iOS 4 iPhone Multitasking (Xcode 4)

PreviousTable of ContentsNext
Integrating iAds into an iOS 4 iPhone App (Xcode 4)Scheduling iOS 4 iPhone Local Notifications (Xcode 4)


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book


Multitasking refers to the ability of an operating system to run more than one application concurrently. The introduction of iOS version 4.0 was met with much fanfare relating to the fact that the operating system now supported multitasking. In actual fact, iOS has always been able to support multitasking and many of the applications bundled with the device (such as the Mail, Phone and iPod apps) have been leveraging the multitasking abilities of iOS since the very first iPhone shipped. What was, in fact, significant about iOS 4 was that some (though not all) of the multitasking capabilities of the operating system were now being made available to us as third party application developers.

Multitasking in iOS, within the context of third part application development at least, is not without some restrictions however. The goal of this chapter, therefore, is to provide an overview of the capabilities, limitations and implementation of multitasking in iOS 4 running on the iPhone.

Understanding iOS Application States

At any given time an iOS application can be in one of a number of different states. Applications in the not running state have either yet to be launched by the user or were previously launched but have been terminated either by the user or the operating system.

An application is in the foreground state when it is the current application displayed to the user. At any one time only one application can be in the foreground state. Applications in the foreground can be in one of two sub-states, namely active or not active.

When in the not active state, the application is running in the foreground but is not actively receiving or handling any events (for example because the system is awaiting a user response to an event such as an incoming phone call or because the screen lock has been activated).

An active application, on the other hand, is running in the foreground and currently receiving events (perhaps due to interaction with the user or via the network).

An application is considered to be in the background state when it is no longer the foreground application. Applications in this state are still executing code either because they have requested additional background execution time to complete a task or because they have requested permission to remain running in the background and, in so doing, have met the criteria (discussed later in the chapter) to do so. An application typically enters the background when the user launches another application, or brings another background application into the foreground. With iOS 4.0 or later it is also possible to launch an application directly into the background.

Applications enter the suspended state when they have been moved to the background and are no longer executing code. The application is still stored in memory preserving its state at the point of suspension but is neither using any CPU cycles nor is it placing additional load on the battery. This state of suspended animation allows the application to be quickly moved into the foreground and execution resumed at the request of the user thereby providing near instantaneous application switching. Suspended applications may be terminated at any time at the discretion of the operating system (typically in order to free up memory resources) so it is essential that applications save any status information to non-volatile storage prior to entering the suspended state.

A Brief Overview of the Multitasking Application Lifecycle

<google>IOSBOX</google> The lifecycle of an iPhone iOS application primarily involves a series of transitions between the various states outlined in the preceding section. At each stage of the lifecycle, calls are made to specific methods in the application’s delegate so that the application can take appropriate action where necessary.

When an application is launched it transitions from not running to either the active or background state. Once the application has loaded the didFinishLaunchingWithOptions delegate method is called. If the newly launched application is entering foreground mode the applicationDidBecomeActive method is then called. If, on the other hand the application is moving directly to the background state (either by design or by necessity), then the applicationDidEnterBackground delegate method is triggered. When a foreground application enters the background the application transitions to the inactive state, triggering a call to the application delegate’s applicationWillResignActive method. This in turn is followed by a transition to background status which is accompanied by a call to the applicationDidEnterBackground method.

If the application has not indicated that is eligible to continue running in the background the application is given 5 seconds to complete any tasks before returning from the applicationDidEnterBackground method. If these tasks cannot be performed in the time given they may be performed by making a call to the beginBackgroundTaskWithExpirationHandler method followed by a call to the endBackgroundTask method when the task is complete. Failure to return from the applicationDidEnterBackground method within the allocated will result in the application being terminated.

When an application is moved from the background to the foreground, the applicationWillEnterForeground method is triggered, followed by a call to applicationDidBecomeActive.

Finally, when an application is about to be terminated (either by the user or the system) the application delegate’s applicationWillTerminate method is called.


Disabling Multitasking for an iOS Application

Multitasking support is the default for all applications developed using the iOS 4.0 SDK or later. In situations where an application is required to exit rather than enter background mode a configuration setting is required in the applications Info.plist file. To achieve this, load the project associated with the app into Xcode and select the Info.plist file from the Supporting Files section of the project navigator panel. In the resulting editor pane, select the bottom most item to create a new key/value pair entry and select the Application does not run in background key from the drop down menu. Once selected, set the value located in the Value column to YES:


Disabling iPhone multitasking in Xcode 4


Checking for Multitasking Support

Multitasking is only supported on the iPhone 3GS and later devices running iOS 4.0 or newer. In the case of devices where multitasking is not supported, applications are simply terminated rather than being placed in the background.

If you are developing an application that relies on multitasking it is recommended that defensive code be implemented to check for multitasking support so that application behavior can be modified to compensate for the missing functionality. This can be achieved using the following code fragment:

-(bool)multitaskingAvailable
{
  UIDevice* device = [UIDevice currentDevice];
  backgroundIsSupported = NO;
  if ([device respondsToSelector:
      @selector(isMultitaskingSupported)])
       backgroundISSupported = device.multitaskingSupported;
  return backgroundIsSupported;
}

When the above method is called it returns either YES or NO depending on whether or not multitasking is supported on the device.

Supported Forms of Background Execution

So far we have looked primarily at the types of applications for which a suspended background state is acceptable to the user. Apple, however, recognizes three categories in which application suspension would be detrimental to the user experience, these being audio, location updates and voice over IP (VOIP).

The background execution modes supported by an application are configured in the application’s Info.plist file using the UIBackgroundModes key and the audio, location and voip values. The value for the key is actually an array allowing an application to register for more than one of the three background execution modes. To configure this setting select the Info.plist file and add the Required background modes key and required the value items. The following figure, for example, illustrates an Info.plist file configured to allow background execution for audio and location updates:


Configuring iOS background modes in Xcode 4


In the case of audio background execution, the audio iOS frameworks responsible for playing sound automatically prevent the application from being suspended whilst in the background. Location based background execution is slightly different in that the application is woken up at required intervals by the operating system in order to handle location related events. For background tracking of location information Apple strongly recommends the use of the significant location changes setting (whereby the application is only notified when the device has moved a significant distance) in order to extend battery life.

Finally, the background operation of VOIP based applications can be configured such that the system monitors network sockets for incoming voice calls and wakes the application up from suspension only when traffic is detected.

The Rules of Background Execution

Apple recommends that a number of rules be observed when running an application in background execution mode:

  • Only perform the minimum tasks when the application is background mode. For example, if the application is playing audio content, the application should only perform the tasks necessary to maintaining the audio stream. All other tasks should be placed on hold until the application is returned to the foreground.
  • Do not perform updates to the user interface of the application. Since the application is in the background the user cannot see the user interface. There is nothing, therefore, to be gained (expect for unnecessarily using CPU cycles and draining the battery) by continuing to update the UI.
  • Do not perform OpenGL ES calls. Doing so will cause your application to be terminated.
  • Always save the state and data information for the application when notification is received that it is entering the background. Even when suspended, an application may be terminated by the system in order to free up resources.
  • Stop using shared resources such as the address book or calendar when the background notification is received to avoid termination.
  • Attempt to release any memory used by the application that can safely be released without impacting the application’s subsequent return to the foreground. The more memory a suspended application is holding on to the more likely it is to be terminated should the system need to free up resources.
  • Cancel Bonjour related services.

Scheduling Local Notifications

Suspended applications and those running in one of the three background execution modes do not, by definition, have access to the display of the iPhone device. In recognition of the fact that background applications may still need to display alert messages to users, Apple introduced the Local Notifications feature in iOS 4. Unlike the Push Notifications functionality available in previous versions of iOS, local notifications allow alerts to be triggered from within the local application without the need to rely on a remote server.

A local notification may be triggered at any time by an executing background application. Suspended applications must, however, schedule the notification to be delivered at a future time as part of the clean up process contained with the applicationDidEnterBackground method. A step-by-step example of how to schedule a local notification within an application entering suspended mode is covered in the chapter entitled Scheduling iOS 4 iPhone Local Notifications.


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book



PreviousTable of ContentsNext
Integrating iAds into an iOS 4 iPhone App (Xcode 4)Scheduling iOS 4 iPhone Local Notifications (Xcode 4)