Apple Push Notification Service

Apple Push Notification Service

Apple Push Notification service (APNs for short) is the centerpiece of the remote notifications feature. It is a robust and highly efficient service for propagating information to iOS and OS X devices. Each device establishes an accredited and encrypted IP connection with the service and receives notifications over this persistent connection. If a notification for an app arrives when that app is not running, the device alerts the user that the app has data waiting for it.

Software developers (“providers”) originate the notifications in their server software. The provider connects with APNs through a persistent and secure channel while monitoring incoming data intended for their client apps. When new data for an app arrives, the provider prepares and sends a notification through the channel to APNs, which pushes the notification to the target device.

In addition to being a simple but efficient and high-capacity transport service, APNs includes a default quality-of-service component that provides store-and-forward capabilities. See Quality of Service for more information.

Provider Communication with Apple Push Notification Service and Scheduling, Registering, and Handling Notifications discuss the specific implementation requirements for providers and iOS apps, respectively.

A Remote Notification and Its Path

Apple Push Notification service transports and routes a remote notification from a given provider to a given device. A notification is a short message consisting of two major pieces of data: the device token and the payload. The device token is analogous to a phone number; it contains information that enables APNs to locate the device on which the client app is installed. APNs also uses it to authenticate the routing of a notification. The payload is a JSON-defined property list that specifies how the user of an app on a device is to be alerted.

Note: For more information about the device token, see Security Architecture; for further information about the notification payload, see The Notification Payload.

The remote-notification data flows in one direction. The provider composes a notification package that includes the device token for a client app and the payload. The provider sends the notification to APNs which in turn pushes the notification to the device.

When a provider authenticates itself to APNs, it sends its topic to the APNs server, which identifies the app for which it’s providing data. The topic is currently the bundle identifier of the target app.

Figure 3-1  Pushing a remote notification from a provider to a client app

Figure 3-1 is a greatly simplified depiction of the virtual network APNs makes possible among providers and devices. The device-facing and provider-facing sides of APNs both have multiple points of connection; on the provider-facing side, these are called gateways. There are typically multiple providers, each making one or more persistent and secure connections with APNs through these gateways. And these providers are sending notifications through APNs to many devices on which their client apps are installed. Figure 3-2 is a slightly more realistic depiction.

Figure 3-2  Pushing remote notifications from multiple providers to multiple devices

The feedback service gives providers information about notifications that could not be delivered—for example, because the target app is no longer installed on that device. For more information, see The Feedback Service.

Quality of Service

Apple Push Notification service includes a default Quality of Service (QoS) component that performs a store-and-forward function.

If APNs attempts to deliver a notification but the device is offline, the notification is stored for a limited period of time, and delivered to the device when it becomes available.

Only one recent notification for a particular app is stored. If multiple notifications are sent while the device is offline, each new notification causes the prior notification to be discarded. This behavior of keeping only the newest notification is referred to as coalescingnotifications.

If the device remains offline for a long time, any notifications that were being stored for it are discarded.

Security Architecture

To enable communication between a provider and a device, Apple Push Notification service must expose certain entry points to them. But then to ensure security, it must also regulate access to these entry points. For this purpose, APNs requires two different levels of trust for providers, devices, and their communications. These are known as connection trust and token trust.

Connection trust establishes certainty that, on one side, the APNs connection is with an authorized provider with whom Apple has agreed to deliver notifications. At the device side of the connection, APNs must validate that the connection is with a legitimate device.

After APNs has established trust at the entry points, it must then ensure that it conveys notifications to legitimate end points only. To do this, it must validate the routing of messages traveling through the transport; only the device that is the intended target of a notification should receive it.

In APNs, assurance of accurate message routing—or token trust—is made possible through the device token. A device token is an opaque identifier of a device that APNs gives to the device when it first connects with it. The device shares the device token with its provider. Thereafter, this token accompanies each notification from the provider. It is the basis for establishing trust that the routing of a particular notification is legitimate.

Note: A device token is not the same thing as the device UDID returned by the identifierForVendor or uniqueIdentifierproperty of UIDevice or any other similar properties such as the advertisingIdentifier property of ASIdentifierManager.

The following sections discuss the requisite components for connection trust and token trust as well as the four procedures for establishing trust.

Service-to-Device Connection Trust

APNs establishes the identity of a connecting device through TLS peer-to-peer authentication. (Note that the system takes care of this stage of connection trust; you do not need to implement anything yourself.) In the course of this procedure, a device initiates a TLS connection with APNs, which returns its server certificate. The device validates this certificate and then sends its device certificate to APNs, which validates that certificate.

Provider-to-Service Connection Trust

Connection trust between a provider and APNs is also established through TLS peer-to-peer authentication. The procedure is similar to that described in Service-to-Device Connection Trust. The provider initiates a TLS connection, gets the server certificate from APNs, and validates that certificate. Then the provider sends its provider certificate to APNs, which validates it on its end. Once this procedure is complete, a secure TLS connection has been established; APNs is now satisfied that the connection has been made by a legitimate provider.

Note that provider connection is valid for delivery to only one specific app, identified by the topic (bundle ID) specified in the certificate. APNs also maintains a certificate revocation list; if a provider’s certificate is on this list, APNs may revoke provider trust (that is, refuse the connection).

Token Generation and Dispersal

Apps must register to receive remote notifications; it typically does this right after it is installed on a device. (This procedure is described in Scheduling, Registering, and Handling Notifications.) The system receives the registration request from the app, connects with APNs, and forwards the request. APNs generates a device token using information contained in the unique device certificate. The device token contains an identifier of the device. It then encrypts the device token with a token key and returns it to the device.

The device returns the device token to the requesting app as an NSData object. The app must then deliver the device token to its provider in either binary or hexadecimal format. Figure 3-3 also illustrates the token generation and dispersal sequence, but in addition shows the role of the client app in furnishing its provider with the device token.

Figure 3-3  Sharing the device token

The form of this phase of token trust ensures that only APNs generates the token which it will later honor, and it can assure itself that a token handed to it by a device is the same token that it previously provisioned for that particular device—and only for that device.

Token Trust (Notification)

After the system obtains a device token from APNs, as described in Token Generation and Dispersal, it must provide APNs with the token every time it connects with it. APNs decrypts the device token and validates that the token was generated for the connecting device. To validate, APNs ensures that the device identifier contained in the token matches the device identifier in the device certificate.

Every notification that a provider sends to APNs for delivery to a device must be accompanied by the device token it obtained from an app on that device. APNs decrypts the token using the token key, thereby ensuring that the notification is valid. It then uses the device ID contained in the device token to determine the destination device for the notification.

Trust Components

To support the security model for APNs, providers and devices must possess certain certificates, certificate authority (CA) certificates, or tokens.

  • Provider: Each provider requires a unique provider certificate and private cryptographic key for validating their connection with APNs. This certificate, provisioned by Apple, must identify the particular topic published by the provider; the topic is the bundle ID of the client app. For each notification, the provider must furnish APNs with a device token identifying the target device. The provider may optionally wish to validate the service it is connecting to using the public server certificate provided by the APNs server.

  • Device: The system uses the public server certificate passed to it by APNs to authenticate the service that it has connected to. It has a unique private key and certificate that it uses to authenticate itself to the service and establish the TLS connection. It obtains the device certificate and key during device activation and stores them in the keychain. The system also holds its particular device token, which it receives during the service connection process. Each registered client app is responsible for delivering this token to its content provider.

APNs servers also have the necessary certificates, CA certificates, and cryptographic keys (private and public) for validating connections and the identities of providers and devices.

The Notification Payload

Each remote notification includes a payload. The payload contains information about how the system should alert the user as well as any custom data you provide. In iOS 8 and later, the maximum size allowed for a notification payload is 2 kilobytes; Apple Push Notification service refuses any notification that exceeds this limit. (Prior to iOS 8 and in OS X, the maximum payload size is 256 bytes.)

For each notification, compose a JSON dictionary object (as defined by RFC 4627). This dictionary must contain another dictionary identified by the key aps. The aps dictionary can contain one or more properties that specify the following user notification types:

  • An alert message to display to the user

  • A number to badge the app icon with

  • A sound to play

The aps dictionary can also contain the content-available property. The content-available property with a value of 1 lets the remote notification act as a “silent” notification. When a silent notification arrives, iOS wakes up your app in the background so that you can get new data from your server or do background information processing. Users aren’t told about the new or changed information that results from a silent notification, but they can find out about it the next time they open your app.

To support silent remote notifications, add the remote-notification value to the UIBackgroundModes array in your Info.plist file. To learn more about this array, see UIBackgroundModes.

If the target app isn’t running when the notification arrives, the alert message, sound, or badge value is played or shown. If the app is running, the system delivers the notification to the app delegate as an NSDictionary object. The dictionary contains the corresponding Cocoa property-list objects (plus NSNull).

Providers can specify custom payload values outside the Apple-reserved aps namespace. Custom values must use the JSON structured and primitive types: dictionary (object), array, string, number, and Boolean. You should not include customer information (or any sensitive data) as custom payload data. Instead, use it for such purposes as setting context (for the user interface) or internal metrics. For example, a custom payload value might be a conversation identifier for use by an instant-message client app or a timestamp identifying when the provider sent the notification. Any action associated with an alert message should not be destructive—for example, it should not delete data on the device.

Important: Delivery of notifications is a “best effort”, not guaranteed. It is not intended to deliver data to your app, only to notify the user that there is new data available.

Table 3-1 lists the keys and expected values of the aps payload.

Table 3-1  Keys and values of the  aps dictionary

Key

Value type

Comment

alert

string or dictionary

If this property is included, the system displays a standard alert. You may specify a string as the value ofalert or a dictionary as its value. If you specify a string, it becomes the message text of an alert with two buttons: Close and View. If the user taps View, the app is launched.

Alternatively, you can specify a dictionary as the value of alert. See Table 3-2 for descriptions of the keys of this dictionary.

badge

number

The number to display as the badge of the app icon.

If this property is absent, the badge is not changed. To remove the badge, set the value of this property to0.

sound

string

The name of a sound file in the app bundle. The sound in this file is played as an alert. If the sound file doesn’t exist or default is specified as the value, the default alert sound is played. The audio must be in one of the audio data formats that are compatible with system sounds; see Preparing Custom Alert Soundsfor details.

content-available

number

Provide this key with a value of 1 to indicate that new content is available. Including this key and value means that when your app is launched in the background or resumed,application:didReceiveRemoteNotification:fetchCompletionHandler: is called.

(Newsstand apps are guaranteed to be able to receive at least one push with this key per 24-hour window.)

Table 3-2 lists the keys and expected values for the alert dictionary.

Table 3-2  Child properties of the  alert property

Key

Value type

Comment

title

string

A short string describing the purpose of the notification. Apple Watch displays this string as part of the notification interface. This string is displayed only briefly and should be crafted so that it can be understood quickly. This key was added in iOS 8.2.

body

string

The text of the alert message.

title-loc-key

string ornull

The key to a title string in the Localizable.strings file for the current localization. The key string can be formatted with %@ and %n$@ specifiers to take the variables specified in the title-loc-args array. See Localized Formatted Strings for more information. This key was added in iOS 8.2.

title-loc-args

array of strings ornull

Variable string values to appear in place of the format specifiers in title-loc-key. See Localized Formatted Strings for more information. This key was added in iOS 8.2.

action-loc-key

string ornull

If a string is specified, the system displays an alert that includes the Close and View buttons. The string is used as a key to get a localized string in the current localization to use for the right button’s title instead of “View”. SeeLocalized Formatted Strings for more information.

loc-key

string

A key to an alert-message string in a Localizable.strings file for the current localization (which is set by the user’s language preference). The key string can be formatted with %@ and %n$@ specifiers to take the variables specified in the loc-args array. See Localized Formatted Strings for more information.

loc-args

array of strings

Variable string values to appear in place of the format specifiers in loc-key. See Localized Formatted Strings for more information.

launch-image

string

The filename of an image file in the app bundle; it may include the extension or omit it. The image is used as the launch image when users tap the action button or move the action slider. If this property is not specified, the system either uses the previous snapshot,uses the image identified by the UILaunchImageFile key in the app’sInfo.plist file, or falls back to Default.png.

This property was added in iOS 4.0.

Note: If you want the device to display the message text as-is in an alert that has both the Close and View buttons, then specify a string as the direct value of alert. Don’t specify a dictionary as the value of alert if the dictionary only has the body property.

Localized Formatted Strings

You can display localized alert messages in two ways:

  • The server originating the notification can localize the text; to do this, it must discover the current language preference selected for the device (see Passing the Provider the Current Language Preference (Remote Notifications)).

  • The client app can store the alert-message strings in its bundle, translated for each localization it supports. The provider includes theloc-key and loc-args keys in the aps dictionary of the notification payload. (For title strings, it includes the title-loc-key andtitle-loc-args keys in the aps dictionary.) When the device receives the notification (assuming the app isn’t running), it uses theseaps-dictionary properties to find and format the string localized for the current language, which it then displays to the user.

Here’s how that second option works in a little more detail.

An app can internationalize resources such as images, sounds, and text for each language that it supports, Internationalization collects the resources and puts them in a subdirectory of the bundle with a two-part name: a language code and an extension of .lproj (for example, fr.lproj). Localized strings that are programmatically displayed are put in a file called Localizable.strings. Each entry in this file has a key and a localized string value; the string can have format specifiers for the substitution of variable values. When an app asks for a particular resource—say a localized string—it gets the resource that is localized for the language currently selected by the user. For example, if the preferred language is French, the corresponding string value for an alert message would be fetched fromLocalizable.strings in the fr.lproj directory in the app bundle. (The app makes this request through the NSLocalizedStringmacro.)

Note: This general pattern is also followed when the value of the action-loc-key property is a string. This string is a key into theLocalizable.strings in the localization directory for the currently selected language. iOS uses this key to get the title of the button on the right side of an alert message (the “action” button).

To make this clearer, let’s consider an example. The provider specifies the following dictionary as the value of the alert property:

"alert" : {
    "loc-key" : "GAME_PLAY_REQUEST_FORMAT",
"loc-args" : [ "Jenna", "Frank"]
}

When the device receives the notification, it uses "GAME_PLAY_REQUEST_FORMAT" as a key to look up the associated string value in theLocalizable.strings file in the .lproj directory for the current language. Assuming the current localization has a Localizable.strings entry such as this:

"GAME_PLAY_REQUEST_FORMAT" = "%@ and %@ have invited you to play Monopoly";

the device displays an alert with the message “Jenna and Frank have invited you to play Monopoly”.

In addition to the format specifier %@, you can %n$@ format specifiers for positional substitution of string variables. The n is the index (starting with 1) of the array value in loc-args to substitute. (There’s also the %% specifier for expressing a percentage sign (%).) So if the entry in Localizable.strings is this:

"GAME_PLAY_REQUEST_FORMAT" = "%2$@ and %1$@ have invited you to play Monopoly";

the device displays an alert with the message “Frank and Jenna have invited you to play Monopoly”.

For a full example of a notification payload that uses the loc-key and loc-arg properties, see Examples of JSON Payloads. To learn more about internationalization, see Internationalization and Localization Guide. String formatting is discussed in Formatting String Objects inString Programming Guide.

Note: You should use the loc-key and loc-args properties—and the alert dictionary in general—only if you absolutely need to. The values of these properties, especially if they are long strings, might use up more bandwidth than is good for performance. Many apps don’t need these properties because their message strings are originated by users.

Examples of JSON Payloads

The following examples of the payload portion of notifications illustrate the practical use of the properties listed in Table 3-1. Properties with “acme” in the key name are examples of custom payload data.

Note: The examples are formatted with whitespace and line breaks for readability. In practice, omit whitespace and line breaks to reduce the size of the payload, improving network performance.

Example 1. The following payload has an aps dictionary with a simple, recommended form for alert messages with the default alert buttons (Close and View). It uses a string as the value of alert rather than a dictionary. This payload also has a custom array property.

{
    "aps" : { "alert" : "Message received from Bob" },
    "acme2" : [ "bang",  "whiz" ]
}

Example 2. The payload in the example uses an aps dictionary to request that the device display an alert message with a Close button on the left and a localized title for the “action” button on the right side of the alert. In this case, “PLAY” is used as a key into theLocalizable.strings file for the currently selected language to get the localized equivalent of “Play”. The aps dictionary also requests that the app icon be badged with the number 5. On Apple Watch, the title key alerts the user to the new request.

{
    "aps" : {
        "alert" : {
            "title" : "Game Request",
            "body" : "Bob wants to play poker",
            "action-loc-key" : "PLAY"
        },
        "badge" : 5,
    },
    "acme1" : "bar",
    "acme2" : [ "bang",  "whiz" ]
}

Example 3. The payload in this example specifies that the device should display an alert message with both Close and View buttons. It also requests that the app icon be badged with the number 9 and that a bundled alert sound be played when the notification is delivered.

{
    "aps" : {
        "alert" : "You got your emails.",
        "badge" : 9,
        "sound" : "bingbong.aiff"
    },
    "acme1" : "bar",
    "acme2" : 42
}

Example 4. The payload in this example uses the loc-key and loc-args child properties of the alert dictionary to fetch a formatted localized string from the app’s bundle and substitute the variable string values (loc-args) in the appropriate places. It also specifies a custom sound and includes a custom property.

{
    "aps" : {
        "alert" : {
            "loc-key" : "GAME_PLAY_REQUEST_FORMAT",
            "loc-args" : [ "Jenna", "Frank"]
        },
        "sound" : "chime.aiff"
    },
    "acme" : "foo"
}

Example 5. The payload in this example includes custom notification actions. Note that the presence of the additional actions array does not affect the default action associated with the alert.

{
   "aps" : {
      "alert” : {
         “body” : "Acme message received from Johnny Appleseed”,
         “action-loc-key” : “VIEW”,
         "actions" : [
            {
               “id" : “delete",
               "title" : "Delete"
            },
            {
               “id" : “reply-to”,
               "loc-key" : “REPLYTO”,
               "loc-args" : [“Jane"]
            }
         ]
      }
      "badge" : 3,
      "sound" : “chime.aiff"
   },
   "acme-account" : "[email protected]",
   "acme-message" : "message123456"
}

你可能感兴趣的:(推送)