使用AWS SNS调用APNS时如何添加自定义请求头?
问题
使用AWS SNS向iOS发送时效性通知时,需按Apple文档要求在请求头中添加apns-priority和apns-expiration字段,但找不到AWS SNS添加这些请求头的正确方式,遇到两个问题:
- AWS官方文档仅提及priority字段,未说明expiration的设置方法;
- 尝试通过
AWS.SNS.MOBILE.APNS.PRIORITY消息属性设置优先级,但未生效。
当前使用的TypeScript代码片段(开发环境采用沙箱):
const params = { Message: JSON.stringify({ APNS_SANDBOX: JSON.stringify({ 'apns-expiration': '0', 'interruption-level': 'time-sensitive', aps: { alert: { body: ' ', }, 'mutable-content': 1, message: message, }, deepLink: deepLink, }), }), MessageStructure: 'json', MessageAttributes: { 'AWS.SNS.MOBILE.APNS.PRIORITY': { DataType: 'String', StringValue: '10' }, }, TargetArn: device.snsArn, }; await this.snsClient.send(new PublishCommand(params));
解决方案
核心修正点
apns-expiration的正确位置:之前将apns-expiration放在APNS消息负载中是错误的,它需要作为AWS SNS的消息属性传递,对应属性键为AWS.SNS.MOBILE.APNS.EXPIRATION。- 优先级设置的正确性:
AWS.SNS.MOBILE.APNS.PRIORITY是正确的属性键,但需确保值为字符串格式的数字('10'对应高优先级,适合时效性通知;'5'对应低优先级)。
修正后的代码
const params = { Message: JSON.stringify({ APNS_SANDBOX: JSON.stringify({ 'interruption-level': 'time-sensitive', aps: { alert: { body: ' ', }, 'mutable-content': 1, message: message, }, deepLink: deepLink, }), }), MessageStructure: 'json', MessageAttributes: { 'AWS.SNS.MOBILE.APNS.PRIORITY': { DataType: 'String', StringValue: '10' // 高优先级,对应APNS即时推送 }, 'AWS.SNS.MOBILE.APNS.EXPIRATION': { DataType: 'String', StringValue: '0' // 0表示永不过期,也可设置具体Unix时间戳字符串 } }, TargetArn: device.snsArn, }; await this.snsClient.send(new PublishCommand(params));
补充说明
apns-expiration的值需为Unix时间戳字符串(单位秒),设置为'0'表示通知永不过期;若需指定过期时间,可计算当前时间加有效期后的时间戳(比如Math.floor(Date.now() / 1000 + 3600).toString()表示1小时后过期)。interruption-level设为time-sensitive需配合优先级10使用,才能让iOS设备将通知标记为时效性推送,跳过专注模式等限制。- 可通过AWS CloudWatch日志查看SNS发送给APNS的请求头,验证
apns-priority和apns-expiration是否正确传递。
内容的提问来源于stack exchange,提问作者manh.vu
相关产品推荐
相关产品推荐

