apns 官方文档

本文介绍了Apple推送通知服务(APNs)中两种不同的通知格式:简单格式与增强格式。简单格式仅支持基本的通知发送功能,而增强格式则增加了错误响应与通知过期等功能,使得开发者能够更高效地管理推送通知。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原文地址:https://developer.apple.com/library/mac/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/LegacyFormat.html#//apple_ref/doc/uid/TP40008194-CH105-SW1

Legacy Information

New development should use the modern format to connect to APNs, as described in The Binary Interface and Notification Format.

These formats do not include a priority; a priority of 10 is assumed.

Simple Notification Format

Figure A-1 shows this format.

Figure A-1  Simple notification format Binary format of a remote notification

The first byte in the legacy format is a command value of 0 (zero). The other fields are the same as the enhanced format. Listing A-1 gives an example of a function that sends a remote notification to APNs over the binary interface using the simple notification format. The example assumes prior SSL connection togateway.push.apple.com (or gateway.sandbox.push.apple.com) and peer-exchange authentication.

Listing A-1  Sending a notification in the simple 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 = 0; /* command number */
        char binaryMessageBuff[sizeof(uint8_t) + sizeof(uint16_t) +
            DEVICE_BINARY_SIZE + sizeof(uint16_t) + MAXPAYLOAD_SIZE];
        /* message format is, |COMMAND|TOKENLEN|TOKEN|PAYLOADLEN|PAYLOAD| */
        char *binaryMessagePt = binaryMessageBuff;
        uint16_t networkOrderTokenLength = htons(DEVICE_BINARY_SIZE);
        uint16_t networkOrderPayloadLength = htons(payloadLength);
 
        /* command */
        *binaryMessagePt++ = command;
 
       /* 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;
}

Enhanced Notification Format

The enhanced format has several improvements over the simple format:

  • Error response. With the simple format, if you send a notification packet that is malformed in some way—for example, the payload exceeds the stipulated limit—APNs responds by severing the connection. It gives no indication why it rejected the notification. The enhanced format lets a provider tag a notification with an arbitrary identifier. If there is an error, APNs returns a packet that associates an error code with the identifier. This response enables the provider to locate and correct the malformed notification.

  • Notification expiration. APNs has a store-and-forward feature that keeps the most recent notification sent to an app on a device. If the device is offline at time of delivery, APNs delivers the notification when the device next comes online. With the simple format, the notification is delivered regardless of the pertinence of the notification. In other words, the notification can become “stale” over time. The enhanced format includes an expiry value that indicates the period of validity for a notification. APNs discards a notification in store-and-forward when this period expires.

Figure A-2 depicts the format for notification packets.

Figure A-2  Enhanced 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 non-zero, APNs tries to deliver the notification at least once. Specify 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.

Listing A-2 composes a remote notification in the enhanced format before sending it to APNs. It assumes prior SSL connection to gateway.push.apple.com (orgateway.sandbox.push.apple.com) and peer-exchange authentication.

Listing A-2  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;
}
### 关于 Apple Push Notification Service (APNs) 的使用配置文档指南 #### 1. APNs 客户端库教程 对于开发者来说,可以利用第三方客户端库来简化与 APNs 的交互过程。例如 `timehop/apns` 是一个用于处理 APNs 推送通知的开源工具[^1]。该库提供了封装好的接口,使得发送消息变得更加便捷。 #### 2. 更新服务器证书 当涉及 APNs 连接时,确保所使用的 SSL/TLS 证书是最新的至关重要。如果旧版证书失效,则可能导致连接中断或其他错误行为。官方建议定期检查并更换证书,并且遵循 Firebase 和 USERTrust RSA 的指导原则完成这一操作[^2]。 #### 3. Go 编程语言中的实现方式 针对采用 Golang 构建应用的需求方而言,存在专门设计用来对接 APNs 功能的一个包——即由 GitCode 托管维护下的 `apn/apns` 库[^3]。此软件包允许开发人员轻松创建自定义负载并通过安全通道传递给目标设备。 以下是简单的代码片段展示如何初始化以及发送一条基本的消息: ```go package main import ( "fmt" "log" apns "github.com/gorush/apns" ) func main() { client := apns.NewClient(&apns.Config{ CertFile: "/path/to/certificate.pem", KeyFile: "/path/to/key.pem", }) payload := &apns.Payload{ Aps: &apns.APS{ Alert: "Hello from Go!", Sound: "default", }, } token := "<device_token>" err := client.Push(token, payload) if err != nil { log.Fatal(err) } fmt.Println("Notification sent successfully!") } ``` #### 4. 利用 Node.js 发送推送通知 Node.js 社区也提供了一个名为 `node-apn` 的模块,它能够协助快速搭建起基于 JavaScript 或 TypeScript 技术栈的应用程序向 iOS 用户分发即时提醒信息[^4]。下面列举了一段基础示范脚本供参考学习之用: ```javascript const apn = require('apn'); // Configure options for connecting to APNS. let options = { token: { key: './authKey.p8', // Path to your private key file (.p8 extension). keyId: '<your_key_id>', // The Key ID obtained when creating an authentication key in App Store Connect. teamId: '<your_team_id>' // Your Developer Team ID found on the Membership page of developer.apple.com/account/. }, production: false // Set this value according to whether you're using sandbox or live environment. }; let apnProvider = new apn.Provider(options); let note = new apn.Notification(); note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires one hour after being issued. note.badge = 3; note.sound = "ping.aiff"; note.alert = "\u201CHello!\u201D"; // Unicode string representation. note.topic = '<bundle_identifier>'; // Replace with actual bundle identifier associated with app registration process at apple side. apnProvider.send(note, ['<device_registration_tokens>']).then((result) => { console.log(result); }); ``` #### 5. Python 中的操作流程 最后,在 Python 生态系统里也有相应的解决方案可供选用。值得注意的是,随着技术迭代升级,原先的一些依赖项可能会被淘汰或者被取代;因此始终要关注最新版本发布情况以便及时调整部署策略[^5]。另外还提到了有关网络环境特殊情况下设置代理参数的方法论说明。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值