The iPhone Developer's Cookbook: Push Notifications
When developers need to communicate directly with users, push notifications provide the solution. They deliver messages directly to the iPhone screen via a special Apple service. Push notifications let the iPhone display an alert, play a custom sound, or update an application badge. In this way, off-phone services connect with an iPhone-based client, letting them know about new data or updates. Unlike most other iPhone development arenas, nearly all the push story takes place off the phone. Developers must create Web-based services to manage and deploy these updates. In this chapter, you learn how push notifications work and dive into the details needed to create your own push-based system.
Introducing Push Notifications
Push notifications, also called remote notifications, refer to a kind of message sent to iPhones by an outside service. These push-based services work with any kind of application that normally checks for information updates. For example, a service might poll for new direct messages on Twitter or respond to sensors for in-home security systems. When new information becomes available for a client, the service pushes that update through Apple's remote notification system. The notification transmits directly to the phone, which has registered to receive those updates.
The key to push is that these messages originate from outside the device itself. They are part of a client-server paradigm that lets Web-based server components communicate with iPhone clients through an Apple-supplied service. With push, developers can send nearly instant updates to iPhones that don't rely on users launching a particular application. Instead, processing occurs on the server side of things. When push messages arrive, the iPhone client can respond by displaying a badge, playing a sound, and/or showing an alert box.
According to Apple, battery life is the single biggest reason for endorsing push notification. When many applications run at once via background processes, these processes can put an undue burden on a device battery, shortening the amount of time available before a recharge is needed. With push, applications can learn about new updates even when they're not running. This lets Apple enforce its strict one-third-party-application-at-a-time policy while at the same time allowing users to receive notifications that are tied to application state changes.
Moving application logic to a server also limits the client-side complexity. Offsite processing provides energy savings for iPhone-based applications. They can now rely on push rather than using the iPhone's local CPU resources to monitor and react to important information changes.
Push's reason for being is not only tied into local resources. It also offers a valuable solution for communicating with Web-based services that goes beyond poll-and-update applications. For example, push might allow you to hook into a recommendation service that produces restaurant suggestions even when an application isn't running or to a calendar service that sends you reminder notices about an upcoming appointment. So don't think about push solely as a battery saver. Also think about it as a conduit for Web services as well.
From social networking to monitoring RSS feeds, push lets iPhone users keep on top of asynchronous data feeds. It offers a powerful solution for connecting iPhone clients to Web-based systems of all kinds. With push, the services you write can connect to your installed iPhone base and communicate updates in a clean, functional manner.
How Push Works
Push notifications aren't just a general way to talk directly to iPhones at will. They are tied to specific applications and require several security checks. A push server can only communicate with those iPhones that are running its application, that are online, and that have opted to receive remote messages. Users have the ultimate say in push updates. They can allow or disallow that kind of communication, and a well-written application lets users opt-in and opt-out of the service at will.
The chain of communication between server and client works like this. Push providers deliver message requests through a central Apple server and via that server to their iPhone clients. In normal use, the server triggers on some event (like new mail or an upcoming appointment) and generates notification data aimed at a specific iPhone device. It sends this message request to the Apple Push Notification Service (APNS). This notification uses JSON formatting and is limited to 256 bytes each, so the information that can be pushed through on that message is quite limited. This formatting and size ensures that APNS limits bandwidth to the tightest possible configuration.
APNS offers a centralized system that negotiates communication with iPhones in the real world. It passes the message through to the designated iPhone. A handler on the iPhone decides how to process the message. As Figure 16-1 shows, push providers talk to APNS, sending their message requests, and APNS talks to phones, relaying those messages to handlers on the unit.
Figure 16-1 Providers send messages through Apple's centralized push notification service to communicate with an iPhone.
Multiple Provider Support
APNS was built to support multiple provider connections, allowing many services to communicate with it at once. It offers multiple gateways into the service so that each push service does not have to wait for availability before sending its message. Figure 16-2 illustrates the many-to-many relationship between providers and iPhones. APNS allows providers to connect at once through multiple gateways. Each provider can push messages to many different iPhones.
Figure 16-2 Apple's Push Notification Service offers many gateways on its provider-facing side, allowing multiple providers to connect in parallel. Each push provider may connect to any number of iPhone devices.
Security
Security is a primary component of remote notifications. The push provider must sign up for a secure sockets layer certificate for each application it works with. Services cannot communicate with APNS unless they authenticate themselves with this certificate. They must also provide a unique key called a token that identifies both the phone to message and the application to notify.
After receiving an authenticated message and device token, APNS contacts the phone in question. Each iPhone or member of the iPhone family such as the iPod touch must be online in some way to receive a notification. They can be connected to a cellular data network or to a Wi-Fi hotspot. APNS establishes a connection with the device and relays the notification request. If the device is offline and the APNS server cannot make a connection, the notification is queued for later delivery.
Upon receiving the request, the iPhone performs a number of checks. Push requests are ignored when the user disables push updates for a given application; users can do so in the Settings application on their iPhone. When updates are allowed, and only then, the iPhone determines whether the client application is currently running. If so, it sends a message directly to the running application via the application delegate. If not, it performs some kind of alert, whether displaying text, playing a sound, or updating a badge.
When an alert displays, users typically have the option to close the alert or tap View. If they choose View, the iPhone launches the application in question and sends it the notification message that it would have received while running. If the user taps Close, the notification gets ignored and the application does not launch.
This pathway, from server to APNS to iPhone to application, forms the core flow of push notifications. Each stage moves the message along the way. Although the multiple steps may sound extensive, in real life the notification arrives almost instantaneously. Once you set up your certificates, identifiers, and connections, the actual delivery of information becomes trivial. Nearly all the work lies in first setting up that chain and then in producing the information you want to deliver.
Make sure you treat all application certificates and device tokens as sensitive information. When storing these items on your server, you must ensure that they are not generally accessible. Should this information hit the wild, it could be exploited by third parties. This would likely result in Apple revoking your SSL push certificate. This would disable all remote notifications for any apps you have sold and might force you to pull the application from the store.
Push Limitations
Push notifications are not reliable. In reality, they can be fairly flaky. Apple does not guarantee the delivery of each notification or the order in which notifications arrive. Never send vital information by push. Reserve this feature for helpful notifications that update the user, but that the user can miss without consequence.
Items in the push delivery queue may be displaced by new notifications. That means that notifications may have to compete and may get lost along the way. Although Apple's feedback service reports failed deliveries (i.e., messages that cannot be properly sent through the push service, specifically to applications that have been removed from a device), you cannot retrieve information regarding bumped notifications. From the APN service point of view, a lost message was still successfully "delivered."