This chapter describes the interfaces that providers use for communication with Apple Push Notification service (APNs) and discusses some of the functions that providers are expected to fulfill.

General Provider Requirements

As a provider you communicate with Apple Push Notification service over a binary interface. This interface is a high-speed, high-capacity interface for providers; it uses a streaming TCP socket design in conjunction with binary content. The binary interface is asynchronous.

The binary interface of the production environment is available through gateway.push.apple.com, port 2195; the binary interface of the development environment is available through gateway.sandbox.push.apple.com, port 2195.

For each interface, use TLS (or SSL) to establish a secured communications channel. The SSL certificate required for these connections is provisioned through the iOS Provisioning Portal. (See “Provisioning and Development” for details.) To establish a trusted provider identity, present this certificate to APNs at connection time using peer-to-peer authentication.

Note: To establish a TLS session with APNs, an Entrust Secure CA root certificate must be installed on the provider’s server. If the server is running OS X, this root certificate is already in the keychain. On other systems, the certificate might not be available. You can download this certificate from the Entrust SSL Certificates website.

As a provider, you are responsible for the following aspects of push notifications:

  • You must compose the notification payload (see “The Notification Payload”).

  • You are responsible for supplying the badge number to be displayed on the application icon.

  • Connect regularly with the feedback service and fetch the current list of those devices that have repeatedly reported failed-delivery attempts. Then stop sending notifications to the devices associated with those applications. See “The Feedback Service” for more information.

If you intend to support notification messages in multiple languages, but do not use the loc-key and loc-args properties of the aps payload dictionary for client-side fetching of localized alert strings, you need to localize the text of alert messages on the server side. To do this, you need to find out the current language preference from the client application. “Scheduling, Registering, and Handling Notifications” suggests an approach for obtaining this information. See “The Notification Payload” for information about the loc-key and loc-args properties.

Best Practices for Managing Connections

You may establish multiple connections to the same gateway or to multiple gateway instances. If you need to send a large number of push notifications, spread them out over connections to several different gateways. This improves performance compared to using a single connection: it lets you send the push notifications faster, and it lets APNs deliver them faster.

Keep your connections with APNs open across multiple notifications; don’t repeatedly open and close connections. APNs treats rapid connection and disconnection as a denial-of-service attack. You should leave a connection open unless you know it will be idle for an extended period of time—for example, if you only send notifications to your users once a day it is ok to use a new connection each day.

The Binary Interface and Notification Formats

The binary interface employs a plain TCP socket for binary content that is streaming in nature. For optimum performance, batch multiple notifications in a single transmission over the interface, either explicitly or using a TCP/IP Nagle algorithm.

Figure 5-1 depicts the format for notification packets.

Figure 5-1  Notification format

The first byte in the notification format is a command value of 1. The remaining fields are as follows:

  • Identifier—An arbitrary value that identifies this notification. This same identifier is returned in a error-response packet if APNs cannot interpret a notification.

  • Expiry—A fixed UNIX epoch date expressed in seconds (UTC) that identifies when the notification is no longer valid and can be discarded. The expiry value uses network byte order (big endian). If the expiry value is positive, APNs tries to deliver the notification at least once. Specify zero (or a value less than zero) to request that APNs not store the notification at all.

  • Token length—The length of the device token in network order (that is, big endian)

  • Device token—The device token in binary form.

  • Payload length—The length of the payload in network order (that is, big endian). The payload must not exceed 256 bytes and must not be null-terminated.

  • Payload—The notification payload.

If you send a notification that is accepted by APNs, nothing is returned.

If you send a notification that is malformed or otherwise unintelligible, APNs returns an error-response packet and closes the connection. Any notifications that you sent after the malformed notification using the same connection are discarded, and must be resent. Figure 5-2 shows the format of the error-response packet.

Figure 5-2  Format of error-response packet

The packet has a command value of 8 followed by a one-byte status code and the same notification identifier specified by the provider when it composed the notification. Table 5-1 lists the possible status codes and their meanings.

Table 5-1  Codes in error-response packet

Status code

Description

0

No errors encountered

1

Processing error

2

Missing device token

3

Missing topic

4

Missing payload

5

Invalid token size

6

Invalid topic size

7

Invalid payload size

8

Invalid token

10

Shutdown

255

None (unknown)

A status code of 10 indicates that the APNs server closed the connection (for example, to perform maintenance). The notification identifier in the error response indicates the last notification that was successfully sent. Any notifications you sent after it have been discarded and must be resent. When you receive this status code, stop using this connection and open a new connection.

Listing 5-1 modifies the code in “Note” to compose a push notification in the enhanced format before sending it to APNs. As with the earlier example, it assumes prior SSL connection to gateway.push.apple.com (or gateway.sandbox.push.apple.com) and peer-exchange authentication.

Listing 5-1  Sending a notification in the enhanced format via the binary interface

static bool sendPayload(SSL *sslPtr, char *deviceTokenBinary, char *payloadBuff, size_t payloadLength)
{
  bool rtn = false;
  if (sslPtr && deviceTokenBinary && payloadBuff && payloadLength)
  {
      uint8_t command = 1; /* command number */
      char binaryMessageBuff[sizeof(uint8_t) + sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint16_t) +
          DEVICE_BINARY_SIZE + sizeof(uint16_t) + MAXPAYLOAD_SIZE];
      /* message format is, |COMMAND|ID|EXPIRY|TOKENLEN|TOKEN|PAYLOADLEN|PAYLOAD| */
      char *binaryMessagePt = binaryMessageBuff;
      uint32_t whicheverOrderIWantToGetBackInAErrorResponse_ID = 1234;
      uint32_t networkOrderExpiryEpochUTC = htonl(time(NULL)+86400); // expire message if not delivered in 1 day
      uint16_t networkOrderTokenLength = htons(DEVICE_BINARY_SIZE);
      uint16_t networkOrderPayloadLength = htons(payloadLength);
 
      /* command */
      *binaryMessagePt++ = command;
 
     /* provider preference ordered ID */
     memcpy(binaryMessagePt, &whicheverOrderIWantToGetBackInAErrorResponse_ID, sizeof(uint32_t));
     binaryMessagePt += sizeof(uint32_t);
 
     /* expiry date network order */
     memcpy(binaryMessagePt, &networkOrderExpiryEpochUTC, sizeof(uint32_t));
     binaryMessagePt += sizeof(uint32_t);
 
     /* token length network order */
      memcpy(binaryMessagePt, &networkOrderTokenLength, sizeof(uint16_t));
      binaryMessagePt += sizeof(uint16_t);
 
      /* device token */
      memcpy(binaryMessagePt, deviceTokenBinary, DEVICE_BINARY_SIZE);
      binaryMessagePt += DEVICE_BINARY_SIZE;
 
      /* payload length network order */
      memcpy(binaryMessagePt, &networkOrderPayloadLength, sizeof(uint16_t));
      binaryMessagePt += sizeof(uint16_t);
 
      /* payload */
      memcpy(binaryMessagePt, payloadBuff, payloadLength);
      binaryMessagePt += payloadLength;
      if (SSL_write(sslPtr, binaryMessageBuff, (binaryMessagePt - binaryMessageBuff)) > 0)
          rtn = true;
  }
  return rtn;
}

Take note that the device token in the production environment and the device token in the development environment are not the same value.

The Feedback Service

The Apple Push Notification Service includes a feedback service to give you information about failed push notifications. When a push notification cannot be delivered because the intended app does not exist on the device, the feedback service adds that device’s token to its list. Push notifications that expire before being delivered are not considered a failed delivery and don’t impact the feedback service. By using this information to stop sending push notifications that will fail to be delivered, you reduce unnecessary message overhead and improve overall system performance.

Query the feedback service daily to get the list of device tokens. Use the timestamp to verify that the device tokens haven’t been reregistered since the feedback entry was generated. For each device that has not been reregistered, stop sending notifications. APNs monitors providers for their diligence in checking the feedback service and refraining from sending push notifications to nonexistent applications on devices.

Note: The feedback service maintains a separate list for each push topic. If you have multiple apps, you must connect to the feedback service once for each app, using the corresponding certificate, in order to receive all feedback.

The feedback service has a binary interface similar to the interface used for sending push notifications. You access the production feedback service viafeedback.push.apple.com on port 2196 and the development feedback service via feedback.sandbox.push.apple.com on port 2196. As with the binary interface for push notifications, use TLS (or SSL) to establish a secured communications channel. You use the same SSL certificate for connecting to the feedback service as you use for sending notifications. To establish a trusted provider identity, present this certificate to APNs at connection time using peer-to-peer authentication.

Once you are connected, transmission begins immediately; you do not need to send any command to APNs. Read the stream from the feedback service until there is no more data to read. The received data is in tuples with the following format:

Figure 5-3  Binary format of a feedback tuple

Timestamp

A timestamp (as a four-byte time_t value) indicating when APNs determined that the application no longer exists on the device. This value, which is in network order, represents the seconds since 12:00 midnight on January 1, 1970 UTC.

Token length

The length of the device token as a two-byte integer value in network order.

Device token

The device token in binary format.

The feedback service’s list is cleared after you read it. Each time you connect to the feedback service, the information it returns lists only the failures that have happened since you last connected.

https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW1

Provider Communication with Apple Push Notification Service的更多相关文章

  1. (转)在SAE使用Apple Push Notification Service服务开发iOS应用, 实现消息推送

    在SAE使用Apple Push Notification Service服务开发iOS应用, 实现消息推送 From: http://saeapns.sinaapp.com/doc.html 1,在 ...

  2. 陌陌架构分享 – Apple Push Notification Service

    http://blog.latermoon.com/?p=878 先描述下基本概念,标准的iPhone应用是没有后台运行的,要实现实时推送消息到手机,需要借助Apple提供的APNS服务. iPhon ...

  3. (转)How to build an Apple Push Notification provider server (tutorial)

    转自:https://blog.serverdensity.com/how-to-build-an-apple-push-notification-provider-server-tutorial/ ...

  4. (转)Apple Push Notification Services in iOS 6 Tutorial: Part 2/2

    转自:http://www.raywenderlich.com/32963/apple-push-notification-services-in-ios-6-tutorial-part-2 Upda ...

  5. (转)Apple Push Notification Services in iOS 6 Tutorial: Part 1/2

    转自:http://www.raywenderlich.com/32960/apple-push-notification-services-in-ios-6-tutorial-part-1 Upda ...

  6. (转)苹果推送通知服务教程 Apple Push Notification Services Tutorial

    本文译自http://www.raywenderlich.com/.原文由iOS教程团队 Matthijs Hollemans 撰写,经原网站管理员授权本博翻译. 在iOS系统,考虑到手机电池电量,应 ...

  7. 远程通知APNs(Apple Push Notification Server)

    推送通知是由应用服务提供商发起的,通过苹果的APNs(Apple Push Notification Server)发送到应用客户端.下面是苹果官方关于推送通知的过程示意图: 推送通知的过程可以分为以 ...

  8. (转)How to renew your Apple Push Notification Push SSL Certificate

    转自:https://blog.serverdensity.com/how-to-renew-your-apple-push-notification-push-ssl-certificate/ It ...

  9. Microsoft Push Notification Service(MPNS)的最佳体验

    如何获得 Microsoft Push Notification Service(MPNS)的最佳体验 有很多同学抱怨MPNS的各种问题,其中包括服务超时.返回各种错误代码不知如何处理等等..今天我用 ...

随机推荐

  1. TamperData火狐插件启用

    今天第一次在准备学习sqlmap的时候看到有人使用了这个TamperData火狐的插件,所以我也安装来看看,光是安装了,但是重启浏览器之后不知道怎么启用,得不到想要的运行界面,所以在这里记录一下,为自 ...

  2. 关于运行SWT程序遇到的一个错误的总结

    具体的错误信息如下: Exception in thread "main" java.lang.SecurityException: SHA1 digest error for o ...

  3. matlab——sparse函数和full函数(稀疏矩阵和非稀疏矩阵转换)

    函数功能:生成稀疏矩阵 使用方法 :S = sparse(A) 将矩阵A转化为稀疏矩阵形式,即矩阵A中任何0元素被去除,非零元素及其下标组成矩阵S.如果A本身是稀疏的,sparse(S)返回S. S ...

  4. always block內省略else所代表的電路

    真 OO无双 之 真乱舞书 寫程式是很快樂的一件事 Since Sep.15,2006 (筆記) always block內省略else所代表的電路 (SOC) (Verilog) Abstract在 ...

  5. linux gpg 使用笔记

    http://linux.chinaunix.net/techdoc/system/2009/04/30/1109541.shtml 一.GnuPG的简介     我们在网上的发送的邮件是明文的,可以 ...

  6. System.Data.SqlClient.SqlError: 对文件……的目录查找失败[转]

    System.Data.SqlClient.SqlError: 对文件……的目录查找失败,出现操作系统错误 3 的处理办法 在还原SQL SERVER数据库时出现了查找目录失败的原因,困扰了我一个多小 ...

  7. Java的内存泄漏_与C/C++对比(转载总结)

    原文网址:http://developer.51cto.com/art/201111/302465.htm Java内存泄露的理解与解决(1)   一般来说内存泄漏有两种情况.一种情况如在C/C++ ...

  8. C# 数据类型映射 (SQLite,MySQL,MSSQL,Oracle)

    一.C# vs SQLite: C# SQLite 字段名 类型 库类型 GetFieldType(#) 转换 备注 F_BOOL bool BIT NOT NULL Boolean F_BOOL_N ...

  9. OC3_字符串分割

    // // main.m // OC3_字符串分割 // // Created by zhangxueming on 15/6/11. // Copyright (c) 2015年 zhangxuem ...

  10. OC_NSString

    // // main.m // OC_NSString // // Created by qianfeng on 15/6/10. // Copyright (c) 2015年 qianfeng. A ...