16.6. Saving and Loading the State of Multitasking Apps

Problem

You want the state of your iOS app to be saved when it is sent to the background and for the same state to resume when the application is brought to the foreground.

Solution

Use a combination of the UIApplicationDelegate protocol’s messages sent to your application delegate and the notifications sent by iOS to preserve the state of your multitasking apps.

Discussion

When an empty iOS application (an application with just one window and no code written for it) is run on an iOS device with support for multitasking for the first time (not from the background), the following UIApplicationDelegate messages will be sent to your app delegate, in this order:

  1. application:didFinishLaunchingWithOptions:

  2. applicationDidBecomeActive:

If the user presses the Home button on her iOS device, your app delegate will receive these messages, in this order:

  1. applicationWillResignActive:

  2. applicationDidEnterBackground:

Once the application is in the background, the user can press the Home button twice and select our application from the list of background applications. (The way our app is brought to the foreground doesn’t really matter. For all we know, another app might launch our app through URI schemes that we can expose in our app.) Once our application is brought to the foreground again, we will receive these messages in the application delegate, in this order:

  1. applicationWillEnterForeground:

  2. applicationDidBecomeActive:

In addition to these messages, ...

Get iOS 7 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.