3.11. Application Services

The state of an application is more important on the iPhone than it is on the desktop. Many events on the iPhone can cause an application to suspend or terminate. These different states occur when the user presses the Home button, locks the screen, or receives a phone call. It's important for an application to know when its state is about to change in order to save any settings, halt threads, or perform other actions. While there's nothing the application can generally do about the state it's about to enter, it can at least take whatever actions are appropriate to prepare for it.

Application services are provided by notifying the application's delegate class to events about to occur. All of the methods listed in this section belong to the UIApplica⁠tionDe⁠legate protocol. The application delegate is specified when you first instantiate the Objective-C portion of the application by calling UIApplicationMain in your main.m file. If you supplied a NIB file, you define the application's delegate inside the Interface Builder template.

3.11.1. Suspending and Resuming

When the device is locked or a phone call comes in, SDK applications are suspended. When this occurs, the delegate's applicationWillResignActive method is notified. This method can be overridden to prepare the application for being suspended, such as closing network connections or saving data:

- (void)applicationWillResignActive:(UIApplication *) application {
    NSLog(@"About to be suspended");

    /* Code to prepare for suspend */
}

While your application is suspended, it will not run in the background. When the application resumes, another method named applicationDidBecomeActive is notified. Here, you can add code to resume where your application left off:

- (void)applicationDidBecomeActive:(UIApplication *) application {
    NSLog(@"Became active");

    /* Code to prepare for resume */
}

When an application is started, its applicationDidBecomeActive method is also notified after its applicationDidFinishLaunching method. Be sure your code can tell the difference between resuming and starting.


3.11.2. Program Termination

A program is terminated when the user presses the Home button or the iPhone is shut down. The applicationWillTerminate method is called whenever an application is about to be cleanly terminated. It is not called when an application is force-quit by holding down the Home button. This method should perform any remaining cleanup of resources, such as making sure all connections are properly closed and performing any other necessary tasks before the program exits:

- (void)applicationWillTerminate:(UIApplication *)application {

    /* Cleanup and shutdown code here */
}