ITP 342 Mobile App Development Notifications
3 Types Apple provides three different types of notifications in ios: NSNotificationCenter, UILocalNotification (Local Notifications), and Remote (Push) Notifications. The three notifications have three very different uses. NSNotificationCenter and Notification Center share a similar name, but are not related.
3 Types 3
4
Notification Center Notification Center is a feature added in ios 5 that allows users to control and manage local and remote notifications. One part of Notification Center is the window shade pulled down from the status bar showing active notifications. The other part of Notification Center is accessed from Settings Notification Center. It allows users to set the type of alert displayed for notifications, change the sound played or even disable notifications completely. 5
6
Local and Push Notifications The essential purpose of both local and push notifications is to enable an application to inform its users that it has something for them for example, a message or an upcoming appointment when the application isn t running in the foreground. The essential difference between local notifications and push notifications is simple: Local notifications are scheduled by an application and delivered on the same device. Push notifications, also known as remote notifications, are sent by your server to the Apple Push Notification service, which pushes the notification to devices. 7
Same to Users Local and push notifications appear the same to the users Users see notifications in the following ways: Displaying an alert or banner Badging the app's icon Playing a sound 8
Same to Users From a user s perspective the meaning of notifications is the same. Both local and remote notifications indicate that there is something of interest in the app. Users control how the device and specific applications installed on the device should handle notifications. They can also selectively enable or disable push notification types (that is, icon badging, alert messages, and sounds) for specific applications. 9
Different to Apps Local and push notifications appear different to apps If your app is frontmost, the application: didreceiveremotenotification: or application: didreceivelocalnotification: method is called on its app delegate. If your app is not frontmost or not running, you handle the notifications by checking the options dictionary passed to the application: didfinishlaunchingwithoptions: of your app delegate for either the UIApplicationLaunchOptionsLocalNotificatio nkey or UIApplicationLaunchOptionsRemoteNotificati onkey key. 10
Local Notifications A local notification is an instance of UILocalNotification with three general kinds of properties: Scheduled time: You must specify the date and time the operating system delivers the notification; this is known as the fire date. You may qualify the fire date with a specific time zone so that the system can make adjustments to the fire date when the user travels. You can also request the operating system to reschedule the notification at a regular interval (weekly, monthly, and so on). Notification type: This category includes the alert message, the title of the action button, the application icon badge number, and a sound to play. Custom data: Local notifications can include a dictionary of custom data. 11
UILocalNotification https:// developer.apple.com/ library/ios/documentation/ iphone/reference/ UILocalNotification_Class/ Reference/Reference.html 12
UILocalNotifications A UILocalNotification is set within an ios app to trigger at a specific time. During setup, you can specify that an Open button be present on the alert presented to the user. When the UILocalNotification is set up, ios adds an entry to Notification Center for the app. This entry allows the user to change if a notification message should be displayed, how the notification is displayed (alert message or notification pull down) and what sound plays. 13
UILocalNotifications When the trigger time is reached, several things can happen, some of them in sequence: If the app is not in the foreground, the notification is sent to Notification Center. If the user has enabled alerts for the app, the type of alert selected will be shown. If the app set up the notification to have an Open button, the app is launched or brought to the foreground if the user touches the button. If the app is not currently launched, it will be and the method application: didfinishlaunchingwithoptions: in the App Delegate is called followed by a call to application: WillEnterForeground: and finally followed by a call to application: didreceivelocalnotification:. 14
UILocalNotifications When the trigger time is reached, several things can happen, some of them in sequence: If the app is launched but is not in the foreground, it is brought to the foreground and the method application: WillEnterForeground: in the App Delegate is called followed by a call to the method application: didreceivelocalnotification:. If the app is in the foreground, the method application: didreceivelocalnotification: in the App Delegate is called bypassing any action from Notification Center. 15
UILocalNotifications Both methods application: didfinishlaunchingwithoptions: and application: didreceivelocalnotification: are passed the notification while application: WillEnterForeground: is not. The method application: didreceivelocalnotification: should be used to take any actions that are required every time a local notification is received. The method application: didfinishlaunchingwithoptions: can be used to take actions specific to when the app is launched because of receiving a local notification. 16
Push Notifications A push notification is a short message that a provider has delivered to the operating system of a device or computer; the operating system, in turn, informs the user of a client application that there is data to be downloaded, a message to be viewed, and so on. If the user enables this feature (on ios) and the application is properly registered, the notification is delivered to the operating system and possibly to the application. Apple Push Notification service is the primary technology for the push-notification feature. 17
Push Notifications Remote notifications, also called Apple Push Notifications (APN), are used to tell an app that something outside the device has occurred. The app can then act on this information. This process requires the action of two remote servers the Apple Push Notification Server (APNS) and a server maintained by the app developer. 18
Remote Notifications https://developer.apple.com/library/ios/ documentation/networkinginternet/ Conceptual/RemoteNotificationsPG/ Chapters/ApplePushService.html 19
Push Notifications The operating system receives a push notification on behalf of the application and alerts the user. Once alerted, users may choose to launch the application, which then downloads the data from its provider. If an application is running when a notification comes in, the application can choose to handle the notification directly. 20
Push Notifications As its name suggests, Apple Push Notification service (APNs) uses a push design to deliver notifications to devices and computers. A push design differs from its opposite, a pull design, in that the recipient of the notification passively listens for updates rather than actively polling for them. A push design makes possible a wide and timely dissemination of information with few of the scalability problems inherent with pull designs. APNs uses a persistent IP connection for implementing push notifications. 21
Push Notifications Most of a push notification consists of a payload: a property list containing APNsdefined properties specifying how the user is to be notified. For performance reasons, the payload is deliberately small. Although you may define custom properties for the payload, you should never use the remotenotification mechanism for data transport because delivery of push notifications is not guaranteed. 22
Push Notifications APNs retains the last notification it receives from a provider for an application on a device; so, if a device comes online and has not received the notification, APNs pushes the stored notification to it. A device running ios receives push notifications over both Wi-Fi and cellular connections. 23
Push Notifications In ios, Wi-Fi is used for push notifications only if there is no cellular connection or if the device is an ipod touch. For some devices to receive notifications via Wi-Fi, the device s display must be on (that is, it cannot be sleeping) or it must be plugged in. The ipad, on the other hand, remains associated with the Wi-Fi access point while asleep, thus permitting the delivery of push notifications. The Wi-Fi radio wakes the host processor for any incoming traffic. Sending notifications too frequently negatively impacts the device s battery life devices must access the network to receive notifications. 24
Notification Center vs. NSNotificationCenter Notification Center manages notifications generated by UILocalNotification and Remote Notifications only. Notifications from NSNotificationCenter (within an app) are not managed by Notification Center, making the naming confusing. NSNotificationCenter dates back to Mac OSX 10.0 while Notification Center was added in ios 5, so there are historical reasons for this unfortunate naming. 25
NSNotificationCenter https://developer.apple.com/library/mac/ documentation/cocoa/reference/foundation/ Classes/nsnotificationcenter_Class/Reference/ Reference.html 26
NSNotificationCenter Since the very first release of MacOS X, NSNotificationCenter has been used to send notifications within an app. These notifications are invisible to users, but allow one part of an app to let another part know something has happened and some action is required. A typical use for this is to notify a view that a download of data from a remote server is complete, and the data needs to be processed and the view updated to reflect it. 27
Notifications Notifications are an incredibly useful way to send messages (and data) between objects that otherwise don't know about each other Think of it like a radio station broadcasting messages: the station (sender) broadcasts the message, and listeners can choose to listen in and receive some (or all) of the broadcast messages For example, you might have a network reachability check in your app delegate, and post notifications whenever the reachability changes Other objects would listen for that notification and react accordingly when the network goes up or down Some Cocoa frameworks send notifications when certain events happen 28
Notifications Suppose we have unsaved changes when the user presses the home button The model could perform one more save before the app enters the background if only it knew Let's explore how the model can ensure that it is notified whenever the app is about to enter the background 29
Notifications In ios 4.0 and up, the application sends notifications when an app is about to move to the background and when it returns from the background Your app's objects and controllers can listen for these notifications and stop actions (or save data) when the app is about to quit, and resume when it becomes active again 30
Limits of Delegation Delegation is a one-to-one relationship UIApplication has one delegate UITextField has one delegate UITableView has one data source and one delegate How can multiple parties learn about an object? 31
Notifications One-to-many broadcasts Any interested party can subscribe One-way communication Source to listener No feedback loop like delegation provides Any class can post notifications You can make your own Notifications are limited to the current process Not distributed or IPC messages 32
Application Notifications UIApplication also posts notifications for many of the same events it messages the delegate on UIApplicationDidBecomeActiveNotification UIApplicationDidChangeStatusBarFrameNotification UIApplicationDidChangeStatusBarOrientationNotification UIApplicationDidEnterBackgroundNotification UIApplicationDidFinishLaunchingNotification UIApplicationDidReceiveMemoryWarningNotification UIApplicationProtectedDataDidBecomeAvailable UIApplicationProtectedDataWillBecomeUnavailable UIApplicationSignificantTimeChangeNotification UIApplicationWillChangeStatusBarOrientationNotification UIApplicationWillChangeStatusBarFrameNotification UIApplicationWillEnterForegroundNotification UIApplicationWillResignActiveNotification UIApplicationWillTerminateNotification 33
UIApplication Events UIApplication applicationdidenterbackground: UIApplicationDelegate UIApplicationDidEnterBackgroundNotification FortunesViewController NSNotificationCenter AnswersViewController FortunesModel 34
Observing Notifications Register with the Notification Center Pass a valid selector // USCFortunesModel.m!! - (id)init {! self = [super init];! if (self) {! [[NSNotificationCenter defaultcenter] addobserver: self! selector: @selector(appdidenterbackground:)! name: UIApplicationDidEnterBackgroundNotification! object: [UIApplication sharedapplication]];! }! return self;! }! Must take a single NSNotification parameter Make sure your selector has a colon 35
Observing Notifications Implement your observer method Remember the NSNotification parameter Call your save method // USCFortunesModel.m!! - (void) appdidenterbackground:(nsnotification *)notification {! NSLog(@"Entering background: %@", notification);! [self save];! }! 36
Removing Notifications You must eventually stop observing Failing to do so may produce a crash later Stop when you have what your want Or unsubscribe when your object goes away The dealloc method is your last chance // USCFortunesModel.m!! - (void) dealloc {! [[NSNotificationCenter defaultcenter] removeobserver:self];! }! 37
Remove Observers The programmer must remember to remove the observer for notifications when they re no longer needed. This is often done in the dealloc method for the class where the notification was registered. The dealloc method exists and is called even when ARC is used for memory management. 38
NSNotificationCenter vs. Delegates NSNotificationCenter can be used in a similar way to delegates, notifying a different part of the app that some action is required. Actions called via NSNotificationCenter can be changed while a delegate method is always the same. It s also possible to have one trigger cause several different actions. As a general rule, if a single, non-changing action is required for a specific trigger, a delegate method may be the best option. If a trigger must sometimes result in one action and other times have a different action, or if a trigger needs to result in multiple actions in different locations, NSNotificationCenter is a better choice. 39
Resources https://developer.apple.com/library/ios/ documentation/networkinginternet/ Conceptual/RemoteNotificationsPG/ Chapters/WhatAreRemoteNotif.html#// apple_ref/doc/uid/tp40008194-ch102-sw1 40