iOS 8以前Local Notification的坑

这两天借着排查“添加的Local Notification到点没有提醒”的机会,对Local Notification, Remote Notification以及相关API做了一个梳理,发现“别有洞天”。

在iOS 8以前,苹果只提供了一个API来获取关于通知相关的东东,[[UIApplication sharedApplication] enabledRemoteNotificationTypes],

The values in the returned bit mask indicate the types of notifications currently enabled for the app. These types are first set when the app calls the registerForRemoteNotificationTypes: method to register itself with Apple Push Notification service. Thereafter, the user may modify these accepted notification types in the Notifications preference of the Settings app. This method returns those initial or modified values.

官方文档中说,它的值取决于之前用registerForRemoteNotificationTypes注册Remote Notification时所设定的types,同时也会根据用户通知中心中的设定而变更,也就是说,enabledRemoteNotificationTypes同时会反映这两种情况。但在实际测试中,发现只要registerForRemoteNotificationTypes注册成功并生成用于发送PUSH的token,不论通知中心中app的设置如何变化(开启通知、关闭通知、单独开启声音、单独关闭提醒等),enabledRemoteNotificationTypes的值都不会改变,严格等同于之前调用registerForRemoteNotificationTypes时设定的入参。这就意味着,只要注册成功过Remote Notification一次,后续无论用户如何调整app的通知设定,enabledRemoteNotificationTypes的返回值都是一样的。

这个“特性”,对于Remote Notification可能还好,因为毕竟触发PUSH是在服务端,在发送的时候,也无法得知本地客户端的用户设置,但对于Local Notification来说,这就是“致命”的,因为根据它开发者无法判断用户是否允许Local Notification,这也就是文章开头“添加的Local Notification到点没有提醒”的原因,因为现有的判断是根据enabledRemoteNotificationTypes,而它又返回了全部3个type,但其实这时用户已经关闭了app的通知。

幸好苹果在iOS 8上解决了这个问题,引入了新的机制,把用户授权App使用本地/远程通知与Remote Notification成功注册并生成token分离开来,前者用[[UIApplication sharedApplication] registerUserNotificationSettings:]来实现,后者通过[[UIApplication sharedApplication] registerForRemoteNotifications]与AppDelegate的[application:didRegisterUserNotificationSettings:]回调来达到,并引入了[[UIApplication sharedApplication] currentUserNotificationSettings],来同步返回用户在通知中心中的设定状态。

最后,很有意思的是,在两个版本中,当App在后台时,通知中心中此App的设定值都会影响到Local Notification是否以及如何被显示,而当在App在前台时,无论通知中心中的设置如何,Local Notification总是同样地进行显示。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 许多集成的步骤个推官网都有了,这里只写关于推送的远程推送和本地通知的步骤和代码。APP在后台时:走苹果的APNS通...
    AllureJM阅读 2,817评论 1 9
  • 极光推送: 1.JPush当前版本是1.8.2,其SDK的开发除了正常的功能完善和扩展外也紧随苹果官方的步伐,SD...
    Isspace阅读 6,812评论 10 16
  • 推送通知注意:这里说的推送通知跟NSNotification有所区别NSNotification是抽象的,不可见的...
    醉叶惜秋阅读 1,569评论 0 3
  • 推送通知 注意:这里说的推送通知跟NSNotification有所区别 NSNotification是抽象的,不可...
    iOS开发攻城狮阅读 4,359评论 1 13
  • 平日里,我是个顽皮的孩子,时不时在家里蹦哒,让家里乱七八糟的,大人们都说我淘气。 可没事做的时候,我就是个安静的美...
    黄轩励阅读 481评论 0 7