Local and Push Notifications in Depth
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.
Local and Push Notifications Appear the Same to Users
Users see notifications in the following ways:
Displaying an alert or banner 弹窗、工具条
Badging the app’s icon 角标数字
Playing a sound 声音
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.
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 theapplication:didFinishLaunchingWithOptions: of your app delegate for either the UIApplicationLaunchOptionsLocalNotificationKey orUIApplicationLaunchOptionsRemoteNotificationKey key. For more details about handling notifications, see “Scheduling, Registering, and Handling Notifications.”
当APP运行在背景或没有启动，那在启动后，应该使用 application:didFinishLaunchingWithOptions: 检查选项词典（options dictionary），选项为 UIApplicationLaunchOptionsLocalNotificationKey 和 orUIApplicationLaunchOptionsRemoteNotificationKey 。具体学习《规划、注册、处理通知》一节。
Examples of Notification Usage
Suppose you are playing chess with your friend online. While you are in the chess app, your friend’s moves appear on the board right away. When you switch to another app—for example, to read email while your friend decides where to move—the app needs a way to notify you when your friend moves. This is a perfect use case for a push notification—something changed outside of the app that is of interest to the user.
The provider for the chess application learns about this move and, seeing that the chess application on your device is no longer connected, sends a push notification to Apple Push Notification service (APNs). Almost immediately, your device—or more precisely, the operating system on your device—receives the notification over the Wi-Fi or cellular connection from APNs. Because your chess application is not currently running, iOS displays an alert similar toFigure 1-1. The message consists of the application name, a short message, and (in this case) two buttons: Close and View. The button on the right is called the action button and its default title is “View”. An application can customize the title of the action button and can internationalize the button title and the message so that they are in the user’s preferred language.
象棋app的开发者获取你的对手走棋的信息后，了解到app没有在连接状态，发送通知到APNs。几乎是在同时，你的设备（准确地说是设备的iOS操作系统）通过Wi-Fi或数据连接得到了通知。因为 app没有处于运行状态，所以，iOS就显示类似于 图1-1的弹窗。 弹窗包含：应用名称、提示内容大概、两个按钮：一个关闭，一个查看。右侧的 View按钮称为 action 按钮，默认标签名为：view，应用可以自己定制或国际化。
Figure 1-1 A notification alert
If you tap the View button, the chess application launches, connects with its provider, downloads the new data, and adjusts the chessboard user interface to show your friend’s move. (Pressing Close dismisses the alert.)
如果按下 View 按钮，象棋应用启动，连接应用app服务器，下载新数据，调整棋盘界面，显示对手走的步子。
OS X Note: The only type of push notification in OS X for non-running applications is icon badging. In other words, an application’s icon in the Dock is badged only if the application isn’t running. If users have not already placed the icon in the Dock, the system inserts the icon into the Dock so that it can badge it (and removes it after the application next terminates). Running applications may examine the notification payload for other types of notifications (alerts and sounds) and handle them appropriately.
Let’s consider a type of application with another requirement. This application manages a to-do list, and each item in the list has a date and time when the item must be completed. The user can request the application to notify it at a specific interval before this due date expires. To effect this, the application schedules a local notification for that date and time. Instead of specifying an alert message, this time the application chooses to specify a badge number (1). At the appointed time, iOS displays a badge number in the upper-right corner of the icon of the application, such as illustrated in Figure 1-2.
另一种情况，比如 to-do列表应用，用户要求app主动通知到期事项。到达到目的，就需要根据日期和时间排列出（Schedules）通知。这种类型不用 弹窗，而是使用 角标数字（1）。
For both local and push notifications, the badge number is specific to an application and can indicate any number of things, such as the number of impending calendar events or the number of data items to download or the number of unread (but already downloaded) email messages. The user sees the badge and launches the app which displays the to-do item or whatever else is of interest to the user.
角标数字 可以表示很多意义，比如 待办事宜数，需要下载的条目数，或未读信息数（maybe已下载）。
Figure 1-2 An application icon with a badge number (iOS)
In iOS, an application can specify a sound file along with an alert message or badge number. The sound file should contain a short, distinctive sound. At the same moment iOS displays the alert or badges the icon, it plays the sound to alert the user to the incoming notification.
More About Local Notifications
Local notifications (available only in iOS) are ideally suited for applications with time-based behaviors, such as calendar and to-do list applications. Applications that run in the background for the limited period allowed by iOS might also find local notifications useful. For example, applications that depend on servers for messages or data can poll their servers for incoming items while running in the background; if a message is ready to view or an update is ready to download, they can then present a local notification immediately to inform their users.
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.
“Scheduling Local Notifications” describes these properties in programmatic detail. Once an application has created a local-notification object, it can either schedule it with the operating system or present it immediately.
Each application on a device is limited to 64 scheduled local notifications. The system discards scheduled notifications in excess of this limit, keeping only the 64 notifications that will fire the soonest. Recurring notifications are treated as a single notification.
More About Push Notifications
An iOS application or a Mac app is often only a part of a larger application based on the client/server model. The client side of the application is installed on the device or computer; the server side of the application has the main function of providing data to its many client applications. (Hence it is termed aprovider.) A client application occasionally connects with its provider and downloads the data that is waiting for it. Email and social-networking applications are examples of this client/server model.
But what if the application is not connected to its provider or even running on the device or computer when the provider has new data for it to download? How does it learn about this waiting data? Push notifications are the solution to this dilemma. 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.
Push notifications serve much the same purpose as a background application on a desktop system, but without the additional overhead. For an application that is not currently running—or, in the case of iOS, not running in the foreground—the notification occurs indirectly. 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.
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.
Most of a push notification consists of a payload: a property list containing APNs-defined 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 remote-notification mechanism for data transport because delivery of push notifications is not guaranteed. For more on the payload, see “The Notification Payload.”
APNs retains the last notification it receives from a provider for an application on a device; so, if a device or computer 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; a computer running OS X receives push notifications over both WiFi and Ethernet connections.
Important: 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.
Adding the remote-notification feature to your application requires that you obtain the proper certificates from the Dev Center for either iOS or OS X and then write the requisite code for the client and provider sides of the application. “Provisioning and Development” explains the provisioning and setup steps, and “Provider Communication with Apple Push Notification Service” and “Scheduling, Registering, and Handling Notifications” describe the details of