iOS apns Device token的获得 以及是否会改变,解决重复推送

来源:互联网 发布:仿真软件有哪些 编辑:程序博客网 时间:2024/06/05 15:29

APP 的推送通知功能对于每个 APP 而言的都是十分重要的,而对于 iOS 开发者来说 APNS 推送服务是必须熟悉掌握的,而注册 APNS 服务时获取的Device token 的变更策略,就是一个需要十分注意的问题。

最近公司的产品遇到了一个问题: 向用户推送消息时,有的用户会出现 重复 收到同一条推送

经过反复排查后终于发现了原因。
我们使用了 腾讯的 信鸽推送 SDK,APP 最初开发时设计的是允许同一用户在多台设备上同时登录的,所以采用的实现为: 用户登录时 注册信鸽推送 然后将 Device token 同步到后台,用户正常注销登录时后台将注销的这台设备的 Device token 设为不可用状态。在推送时查询用户相关的 Device token 调用信鸽 API 进行按设备推送 。这样用户同时登录的多台设备都可以收到推送。
但是由于失误,在账号进行注销登录时也没有 调用 信鸽的 API 注销该设备的推送,也就造成了只要一台设备的 Device token 发生了改变、而用户又没有正常的注销账号,该用户在后台就会有多条 可用 状态的 Device token 记录,而后台在调用 信鸽 API 的时候并没有进行 同一账号 只调用一条 Device token记录进行设备推送的限制,导致了同一设备 重复 收到同一条推送(简单说就是有多条Device token指向了同一台设备)。

而得出这个结论源于我们对Device token改变的测试

在删除手机上的 APP 之后,再次下载安装,Device token 改变了。

也就是说 通过 APNS 获取的 Device token 的变化比我们认为的难度要低得多。

再次查阅官方文档是这样写的:

If the user restores backup data to a new device or computer, or reinstalls the operating system, the device token changes

An application should register every time it launches and give its provider the current token

大致是说,当进行备份恢复、或恢复出厂设置之类的操作时,Device token会发生改变,建议 APP 在每次启动时都获取Device token。
此外普遍认为还有一种情况也会改变Device token,就是在 iOS 大版本升级时。

但是经过我们的测试以及后台数据库中不少用户都拥有多条Device token记录表明,Device token还是比较容易发生改变的。
所以在推送集成中,一定要注意进行新旧Device token的对比,使用第三方(信鸽、极光等)要在账户注销时调用 第三方的API 注销推送,以及在使用Device token进行推送时只取最新的一条Device token,这样就避免存在多个token指向同一台设备的问题。

此外需要注意的一点是,获取Device token时联网状态的改变。

在第一次调用registerForRemoteNotificationTypes方法时没有联网,则既不会调用didRegisterForRemoteNotificationsWithDeviceToken,也不会调用didFailToRegisterForRemoteNotificationsWithError

在第一次调用registerForRemoteNotificationTypes注册成功后,之后即使没有联网,再调用registerForRemoteNotificationTypes时都会以最上一次的device token作为参数回调didRegisterForRemoteNotificationsWithDeviceToken方法。

(官方描述)

If your application has previously registered, calling registerForRemoteNotificationTypes: results in the operating system passing the device token to the delegate immediately without incurring additional overhead.

官方文档地址
https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/Introduction.html#//apple_ref/doc/uid/TP40008194-CH1-SW1

1 0