云旗工人APNS2
使用新的HTTP/2协议与JSON网络代号连接到苹果的Push通知服务的客户端.
分叉通知
这是原作的叉子 apns2 (韩语) 支持 Cloudflare 工人的软件包。 原包有多个依赖性,与Cloudflare工人运行时间不相容. 这种叉去除这些依赖,取而代之的是本地Cloudflare工人API.
创建客户端
使用签名密钥创建APNS客户端 :
import { ApnsClient } from 'apns2'
const client = new ApnsClient({
team: `TFLP87PW54`,
keyId: `123ABC456`,
signingKey: fs.readFileSync(`${__dirname}/path/to/auth.p8`),
defaultTopic: `com.tablelist.Tablelist`,
requestTimeout: 0, // optional, Default: 0 (without timeout)
keepAlive: true, // optional, Default: 5000
})
发送通知
基础
发送带信息的基本通知 :
import { Notification } from 'apns2'
const bn = new Notification(deviceToken, { alert: 'Hello, World' })
try {
await client.send(bn)
} catch (err) {
console.error(err.reason)
}
发送带有信息和选项的基本通知:
import { Notification } from 'apns2'
const bn = new Notification(deviceToken, {
alert: 'Hello, World',
badge: 4,
data: {
userId: user.getUserId
}
})
try {
await client.send(bn)
} catch (err) {
console.error(err.reason)
}
安静
使用 content-available 键 :
import { SilentNotification } from 'apns2'
const sn = new SilentNotification(deviceToken)
try {
await client.send(sn)
} catch (err) {
console.error(err.reason)
}
说明: 苹果建议 选择 content-available 发去旗帜是为了让一个通知真正沉默,并在背景中唤醒您的应用程序. 因此,该类不接受构造器中的任何附加选项.
许多
同时发送多个通知 :
import { Notification } from 'apns2'
const notifications = [
new Notification(deviceToken1, { alert: 'Hello, World' }),
new Notification(deviceToken2, { alert: 'Hello, World' })
]
try {
await client.sendMany(notifications)
} catch (err) {
console.error(err.reason)
}
高级
要完全控制驱动通知包,请使用底盘 Notification 类 :
import { Notification } from 'apns2'
const notification = new Notification(deviceToken, {
aps: { ... }
})
try {
await client.send(notification)
} catch(err) {
console.error(err.reason)
}
可用选项可见于 APNS 有效载荷选项
处理错误
所有错误定义在 ./lib/errors.js 直接从 APNS 表4 数据
您可以在 APNS 客户端中附加一个错误处理器来方便地聆听这些错误 :
import { Errors } from 'apns2'
// Listen for a specific error
client.on(Errors.badDeviceToken, (err) => {
// Handle accordingly...
// Perhaps delete token from your database
console.error(err.reason, err.statusCode, err.notification.deviceToken)
})
// Listen for any error
client.on(Errors.error, (err) => {
console.error(err.reason, err.statusCode, err.notification.deviceToken)
})
环境
默认情况下,APNS客户端会连接到生产推取通知服务器. 这与通过选项相同:
const client = new ApnsClient({
host: 'api.push.apple.com'
...
})
要连接到开发驱动通知服务器, 请通过选项 :
const client = new ApnsClient({
host: 'api.sandbox.push.apple.com'
...
})
所需资源
apns2 需要节点.js v16 或稍后