Scheduling iOS 4 iPhone Local Notifications

From Techotopia
Revision as of 14:44, 5 May 2016 by Neil (Talk | contribs) (Text replacement - "<table border="0" cellspacing="0" width="100%">" to "<table border="0" cellspacing="0">")

Jump to: navigation, search
PreviousTable of ContentsNext
An Overview of iOS 4 iPhone MultitaskingGetting iPhone Location Information using the iOS 4 Core Location Framework


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book


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 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 might need to notify the user of 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 4 iPhone Multitasking to develop a simple iPhone application that, when placed into the background by the user, schedules a local notification event for a future time.


Contents


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 View-based Application template. When prompted to do so name the project localNotify.

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 4 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 localNotifyAppDeleage.m file. Within the main Xcode project window, 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

<google>IOSBOX</google> 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 and must be in Linear PCM, MA4 (IMA/ADPCM), uLaw or aLaw format. 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 copy an audio file from the Mac OS X system on which Xcode is running and use it when scheduling the notification. To locate this file open the Finder tool, navigate to the Macintosh HD/System/Library/Sounds directory and locate a file named Glass.aiff (AIFF being PCM format). Once located, drag this file and drop it onto the Resources category located in the Groups & Files panel in the main Xcode project window and click the Add 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 of the notification. 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 Glass.aiff file:

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

        NSDate *alertTime = [[NSDate date] dateByAddingTimeInterval:10];
        UIApplication* app = [UIApplication sharedApplication];
    UILocalNotification* notifyAlarm = [[[UILocalNotification alloc] init] autorelease];
    if (notifyAlarm)
    {
        notifyAlarm.fireDate = alertTime;
        notifyAlarm.timeZone = [NSTimeZone defaultTimeZone];
        notifyAlarm.repeatInterval = 0;
        notifyAlarm.soundName = @"Glass.aiff";
        notifyAlarm.alertBody = @"Staff meeting in 30 minutes";

        [app scheduleLocalNotification:notifyAlarm];
    }

}

Testing the Application

To test the application, save the changes to the localNotifyAppDeleage.m file and click on the build and 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 glass sound from the audio file:

An iOS 4 iPhone local notification message in the iOS Simulator


Clicking on the View button contained within the notification window will return the localNotify application to the foreground. The Close button simply dismisses the notification window leaving the current foreground application (assuming one is running) unchanged.

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 objectAtIndex: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.


Learn SwiftUI and take your iOS Development to the Next Level
SwiftUI Essentials – iOS 16 Edition book is now available in Print ($39.99) and eBook ($29.99) editions. Learn more...

Buy Print Preview Book



PreviousTable of ContentsNext
An Overview of iOS 4 iPhone MultitaskingGetting iPhone Location Information using the iOS 4 Core Location Framework