美文网首页
UNNotificationSettings属性详解(准确的判断

UNNotificationSettings属性详解(准确的判断

作者: _小浪蹄子 | 来源:发表于2021-09-18 10:08 被阅读0次

    今天在解决一个收不到推送的问题时,才发现自己之前对UNNotificationSettings的理解有误,所以判断推送开关是否打开的判断也是错的。。。

    所以又重新研究了下UNNotificationSettings,简单总结下,记录下自己踩过的坑。

    先上结论:

    iOS10及以上:

    用户是否打开推送开关的判断很简单,就是UNNotificationSettings的authorizationStatus,

    notDetermined就是用户还没有点,

    denied就是用户点了不同意,

    authorized就是用户点了同意。

    注意,如果是notDetermined,那设置里面都不会有通知设置这个选项

    iOS8及iOS9:

    就是UIApplication.shared.isRegisteredForRemoteNotifications,true就是同意,false就是没同意或者未确定;

    所以统一的判断方法如下:

    funcisNotificationEnabled(handle:@escaping(Bool)->Void){if#available(iOS10.0,*){UNUserNotificationCenter.current().getNotificationSettings(completionHandler:{(setting)in//如果授权状态是notDetermined,那其他所有的setting都是0(notSupported)//如果授权状态是deny,那所有其他的setting都是1(disabled)//如果授权状态是authorized,其他设置的值才有意义DispatchQueue.main.async(execute:{ifsetting.authorizationStatus==.authorized{handle(true)}else{handle(false)}})})}else{//YES if the app is registered for remote notifications and received its device token or NO if registration has not occurred, has failed, or has been denied by the user.letresult=UIApplication.shared.isRegisteredForRemoteNotificationshandle(result)}}

    都是认为用户明确点了同意返回true,其他情况返回false

    iOS7及之前:

    貌似只能用[[UIApplication sharedApplication] enabledRemoteNotificationTypes] == UIUserNotificationTypeNone来判断,但我已经没有iOS7的设备或模拟器测试了,所以这个不确定。。。

    详细解释:

    iOS10苹果重构了整个通知框架,推出了UserNotifications这个框架,详见喵神博客(https://onevcat.com/2016/08/notification/

    开发者可以拿到更详细的app通知设置,即UNNotificationSettings,其属性与设置里的对应关系如图

    设置UI与UNNotificationSettings属性对应关系

    明确的一一对应:authorizationStatus是总开关,

    当authorizationStatus是0(notDetermined)时,其他的setting都是0(none或者notSupported)

    当authorizationStatus是1(denied)时,其他的setting都是1(disabled)

    当authorizationStatus是2(authorized)时,其他的setting的值就是UI上开关设置的值

    就这么简单!

    (天真的我原来居然想当然的以为notificationCenterSetting才是开关是否打开的属性,authorizationStatus只是是否授权的状态。。。真是很傻很天真)

    iOS8和iOS9更简单,就是UIApplication.shared.isRegisteredForRemoteNotifications,苹果官方文档上写了:

    YES if the app is registered for remote notifications and received its device token or NO if registration has not occurred, has failed, or has been denied by the user.

    之前用UIApplication.shared.currentUserNotificationSettings == []来判断是否开了通知是不准确的,因为用户其实是可以打开推送开关,然后把所有的设置类型都设置为关。。。当然你说这种跟关了总开关一样,这就看怎么定义了,用户已经聪明到通过这种方式来避免被推送提醒烦了(会这么做的应该也是程序猿吧?),app还提示没打开推送,那就只能卸载才能不被烦了吧!

    转载自:https://www.jianshu.com/p/61dd9dd431a9

    相关文章

      网友评论

          本文标题:UNNotificationSettings属性详解(准确的判断

          本文链接:https://www.haomeiwen.com/subject/hlvegltx.html