Scheduling iOS 7 Local Notifications

From Techotopia
Revision as of 13:42, 10 October 2013 by Neil (Talk | contribs) (New page: <table border="0" cellspacing="0" width="100%"> <tr> <td width="20%">Previous<td align="center">[[iOS 7 App Development Essentials|Table o...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
PreviousTable of ContentsNext
An iOS 7 Background Transfer Service TutorialAn Overview of iOS 7 Application State Preservation and Restoration


<google>BUY_IOS7</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 device (on devices supporting vibration).

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 iOS 7 Multitasking, Background Transfer Service and Fetching by developing a simple iOS application that, when placed into the background by the user, schedules a local notification event for a future time.


Contents


Creating the Local Notification 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 or iPad iOS project using the Single View Application template. When prompted to do so, name the product and class prefix LocalNotify.

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 named bell_tree.mp3 which can be found in the audiofiles folder of the sample code archive which may be downloaded using the following URL:

http://www.ebookfrenzy.com/web/ios7

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.


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 iOS 7 Multitasking, Background Transfer Service and Fetching). 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.
     */
}

<google>BUY_IOS7</google>

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 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. Once the application has loaded, press the device home button to place the app into background mode (if using the iOS Simulator, select the Hardware -> Home menu option). After 10 seconds have elapsed the notification should appear accompanied by the sound from the audio file as illustrated in Figure 63-1.


An iOS 7 Local Notification Triggered

Figure 63-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_IOS7</google>



PreviousTable of ContentsNext
An iOS 7 Background Transfer Service TutorialAn Overview of iOS 7 Application State Preservation and Restoration