Scheduling iOS 6 iPhone Local Notifications

Revision as of 20:35, 19 December 2012 by Neil (Talk | contribs) (Testing the Application)

Revision as of 20:35, 19 December 2012 by Neil (Talk | contribs) (Testing the Application)

PreviousTable of ContentsNext
An Overview of iOS 6 iPhone MultitaskingAn Overview of iOS 6 Application State Preservation and Restoration


<google>BUY_IOS6</google>


Local Notifications were introduced with iOS 4.0 and provide a mechanism for an application to schedule an alert to notify the user about an event. These notifications take the form of an alert box or notification panel containing a message accompanied by a sound and the vibration of the iPhone device.

The primary purpose of local notifications is to provide a mechanism for a suspended or background application to gain the attention of the user. For example, an audio streaming app might need to notify the user of the loss of network connection or a calendar based application an approaching appointment. Local notifications are similar to the push notification system introduced with iOS 3.0 with the primary difference that notifications are scheduled locally by the application and so do not require the involvement of a remote server.

The goal of this chapter is to build upon the groundwork established in An Overview of iOS 6 iPhone Multitasking by developing a simple iPhone application that, when placed into the background by the user, schedules a local notification event for a future time.

Creating the Local Notification iPhone App Project

The first step in demonstrating the use of local notifications is to create a new Xcode project. Begin by launching Xcode and selecting the options to create a new iPhone iOS project using the Single View Application template. When prompted to do so name the product and class prefix LocalNotify and verify that the Automatic Reference Counting and Storyboard options are enabled.

Locating the Application Delegate Method

The goal of this exercise is to configure a local notification to be triggered 10 seconds after our application enters the background (for additional information on background and suspended applications refer to An Overview of iOS 6 iPhone Multitasking). When an application is placed in the background, the application delegate’s applicationDidEnterBackground method is triggered. It is within this method, therefore, that the code to schedule the local notification must be placed. In the case of this example, a template method can be found in the LocalNotifyAppDelegate.m file. Within the main Xcode project navigator panel, select this file and scroll down until the method comes into view:

- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
}

Adding a Sound File to the Project

When a local notification is triggered, the option is available to play a sound to gain the user’s attention. If such an audio alert is required the corresponding sound file must be added to the application project resources. If no sound file is specified, the default is for the notification to be silent (though the iPhone device will still vibrate).

For the purposes of this exercise, we will use a public domain sound clip file which may be downloaded using the following URL:

http://www.ebookfrenzy.com/code/bell_tree.mp3

Once downloaded, drag this file and drop it onto the Supporting Files category located in the Xcode project navigator panel and click the Finish button in the resulting panel. The audio file should now be included in the list of resources for the project ready to be accessed by the application code.

Scheduling the Local Notification

Local notifications require the use of the UILocalNotification class combined with an NSDate object configured with the date and time that the notification is to be triggered. Properties may also be set to specify the text to be displayed to the user, an optional repeat interval and a message to be displayed to the user in the alert box. With these requirements in the mind, the following code creates an NSDate object based on the current date and time plus 10 seconds. This date object is then used to schedule a notification with no repeats, a text message and the sound from the audio file:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    NSDate *alertTime = [[NSDate date]
          dateByAddingTimeInterval:10];
    UIApplication* app = [UIApplication sharedApplication];
    UILocalNotification* notifyAlarm = [[UILocalNotification alloc]
          init];
    if (notifyAlarm)
    {
        notifyAlarm.fireDate = alertTime;
        notifyAlarm.timeZone = [NSTimeZone defaultTimeZone];
        notifyAlarm.repeatInterval = 0;
        notifyAlarm.soundName = @"bell_tree.mp3";
        notifyAlarm.alertBody = @"Staff meeting in 30 minutes";
        [app scheduleLocalNotification:notifyAlarm];
    }
}

Testing the Application

To test the application click on the Run tool bar button located in the Xcode project window. After compiling and linking the application, it will load and run in the iOS Simulator. Once the application has loaded into the iPhone simulator, click on the device home button to place the app into background mode. After 10 seconds have elapsed the notification should appear accompanied by the sound from the audio file as illustrated in Figure 56-1.


<google>ADSDAQBOX_FLOW</google> A local notification on an iOS 6 based iPhone

Figure 56-1

Cancelling Scheduled Notifications

Previously scheduled notifications may be cancelled by obtaining a list of outstanding notifications. These notifications are provided in the form of an NSArray object, the contents of which may be used to cancel individual notifications using the cancelLocalNotification method. All currently scheduled notifications may also be cancelled using the cancelAllLocalNotifications method as outlined in the following code fragment:

UIApplication* app = [UIApplication sharedApplication];
NSArray*    oldNotifications = [app scheduledLocalNotifications];

if ([oldNotifications count] > 0)
    [app cancelAllLocalNotifications];

Immediate Triggering of a Local Notification

In addition to the cancellation of a local notification, previously scheduled notifications may be triggered to present immediately to the user irrespective of the fireDate property setting. For example, the following code identifies the list of currently scheduled notifications and then triggers the first notification in the array for immediate presentation:

NSArray *notifications = [app scheduledLocalNotifications];
if ([notifications count] > 0)
    [app presentLocalNotificationNow:notifications[0]];

Note that notifications presented using the presentLocalNotificationNow method will still trigger again when the specified fireDate is reached unless they are specifically cancelled.

Summary

Local notifications were introduced in iOS 4.0 alongside multitasking support as a way for iOS applications placed in the background or in a suspended state to notify the user of an event. In this chapter we have worked through an example of scheduling a local notification for a future time when an application receives notification that it is transitioning to the background state. Also covered were the steps necessary to cancel pending notifications and to trigger the immediate presentation of a notification regardless of the scheduled delivery time.


<google>BUY_IOS6</google>



PreviousTable of ContentsNext
An Overview of iOS 6 iPhone MultitaskingAn Overview of iOS 6 Application State Preservation and Restoration