Home > Articles > Programming > C/C++

  • Print
  • + Share This
This chapter is from the book

Handling Background Suspension

In the second tutorial, we handle background suspension. As previously noted, you don't have to do anything to support this other than build your project with the iOS 4.x development tools. That said, we use this example as an opportunity to prompt users when they return to the application after it was backgrounded.

For this example, we update the ImageHop application from Hour 8, "Handling Images, Animation, and Sliders." It is conceivable (work with me here, folks!) that a user will want to start the bunny hopping, exit the application, and then return to exactly where it was at some time in the future.

To alert the user when the application returns from suspension, we'll edit the application delegate method applicationWillEnterForeground. Recall that this method is invoked only when an application is returning from a backgrounded state. Open ImageHopAppDelegate.m and implement the method, as shown in Listing 21.1.

Listing 21.1.

- (void)applicationWillEnterForeground:(UIApplication *)application {
    UIAlertView *alertDialog;
    alertDialog = [[UIAlertView alloc]
                   initWithTitle: @"Yawn!"
                   message:@"Was I asleep?"
                   delegate: nil
                   cancelButtonTitle: @"Welcome Back"
                   otherButtonTitles: nil];
    [alertDialog show];
    [alertDialog release];
}

Within the method, we declare, initialize, show, and release an alert view, exactly as we did in the "Getting Attention" tutorial in Hour 10, "Getting the User's Attention." After updating the code, build and run the application. Start the ImageHop animation, and then use the Home button to background the app.

After waiting a few seconds (just for good measure), open ImageHop again using the task manager or its application icon (not Build and Run!). When the application returns to the foreground, it should pick up exactly where it left off and present you with the alert shown in Figure 21.3.

Figure 21.3

Figure 21.3 The application WillEnterFore-ground method is used to display an alert upon returning from the background.

  • + Share This
  • 🔖 Save To Your Account