关于iOS 7 Background Remote Notification(推送唤醒)
更新说明
更新记录:
- 2016 年 8 月,第一版
- 2017 年 8 月,增加配置极光推送的注意事项
Background Remote Notification简介
Remote Notifications是 iOS7 在推送方面最大的变化,它允许应用收到通知后在后台(background)状态下运行一段代码,可用于从服务器获取内容更新。功能使用场景:(多媒体)聊天,Email更新,基于通知的订阅内容同步等功能,提升了终端用户的体验。
如何设置Remote notifications
客户端设置
需要在Xcode 中修改应用的 Capabilities 开启Remote notifications,如图:
当注册了Backgroud Modes -> Remote notifications 后,notification 处理函数一律切换到下面函数,后台推送代码也在此函数中调用。
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
这个函数也是iOS8之后获取远程推送调用的方法。
服务端设置
这个很重要,推送消息携带 content-available: 1 是Background 运行的必须参数,如果不携带此字段则与iOS7 之前版本的普通推送一样。
服务端payload格式:aps增加content-available字段,类似于:
payload example:
{"aps":{"alert":"example", "sound":"default", "badge": 1, "category":"reply","content-available":"1"
}}
这里集成的是极光推送,参考极光推送 Push API v3 的文档,发现了iOS 平台上发送 APNS 通知的规范。其中支持的字段中关键字 content-available 的类型为 boolean 。
如果该字段为 true 说明是 Background Remote Notification ,如果不携带此字段则是普通的 Remote Notification 。
这里需要特别注意的是服务器在配置 content-available: ture 时的正确性。如图,后台以java为例。
最后,当应用在后台挂起时,发起一个 Background Remote Notification(推送唤醒) 。客户端获取的数据,如下:
userInfo = {
"_j_msgid" = 2632357907;
aps = {
alert = "\U6717\U81f4\U96c6\U56e2\U9738\U5dde\U5e02(\U53bf\U7ea7)\U603b\U4ee3\U7406\U5546\U5bb6\U60a8\U597d\Uff01\U60a8\U7684\U5e97\U94fa\U53c8\U6709\U65b0\U8ba2\U5355\U4e86\Uff0c\U8ba2\U5355\U53f73cef6682b73ca,\U8bf7\U53ca\U65f6\U767b\U5f55\U5546\U57ce\U8fdb\U884c\U8ba2\U5355\U5ba1\U6838\U3002";
badge = 1;
category = identifier;
sound = default;
content-available = 1;
};
}
参考资料
配置极光推送的注意事项
使用极光测试生产环境下的推送时,发现无论通过我们自己的后台还是极光的后台使用Register ID发送通知,手机都无法收到通知。而在开发环境下是可以收到的。后来查了下极光文档中使用JPush iOS SDK注意事项:
如果你是直接运行安装到测试设备(运行调试状态),那你的安装的应用的证书环境只有可能是开发环境或者通配的。
而我恰恰是通过Xcode装的程序。
后记
关于 Background Remote Notification(推送唤醒) 早在一年前就使用过,当时调研调试花费了大量时间。没想到现在又遇到了这个问题。结果,我又在阴沟里翻了船。可见做笔记,写博客总结的重要性。希望第三次闭着眼睛就能跳过这个坑。
–EOF–
若无特别说明,本站文章均为原创,转载请保留链接,谢谢