今天在解決一個(gè)收不到推送的問題時(shí)椅野,才發(fā)現(xiàn)自己之前對(duì)UNNotificationSettings的理解有誤,所以判斷推送開關(guān)是否打開的判斷也是錯(cuò)的鳄橘。。术徊。
所以又重新研究了下UNNotificationSettings鲸湃,簡(jiǎn)單總結(jié)下,記錄下自己踩過的坑笋除。
先上結(jié)論:
iOS10及以上:
用戶是否打開推送開關(guān)的判斷很簡(jiǎn)單炸裆,就是UNNotificationSettings的authorizationStatus,
notDetermined
就是用戶還沒有點(diǎn)国拇,
denied
就是用戶點(diǎn)了不同意,
authorized
就是用戶點(diǎn)了同意也殖。
注意务热,如果是notDetermined
,那設(shè)置里面都不會(huì)有通知設(shè)置這個(gè)選項(xiàng)
iOS8及iOS9:
就是UIApplication.shared.isRegisteredForRemoteNotifications
捆毫,true就是同意冲甘,false就是沒同意或者未確定;
所以統(tǒng)一的判斷方法如下:
func isNotificationEnabled(handle: @escaping (Bool) -> Void) {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (setting) in
//如果授權(quán)狀態(tài)是notDetermined,那其他所有的setting都是0(notSupported)
//如果授權(quán)狀態(tài)是deny嫁审,那所有其他的setting都是1(disabled)
//如果授權(quán)狀態(tài)是authorized赖晶,其他設(shè)置的值才有意義
DispatchQueue.main.async(execute: {
if setting.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.
let result = UIApplication.shared.isRegisteredForRemoteNotifications
handle(result)
}
}
都是認(rèn)為用戶明確點(diǎn)了同意返回true遏插,其他情況返回false
iOS7及之前:
貌似只能用[[UIApplication sharedApplication] enabledRemoteNotificationTypes] == UIUserNotificationTypeNone來判斷,但我已經(jīng)沒有iOS7的設(shè)備或模擬器測(cè)試了胳嘲,所以這個(gè)不確定。了牛。。
詳細(xì)解釋:
iOS10蘋果重構(gòu)了整個(gè)通知框架甫窟,推出了UserNotifications這個(gè)框架蛙婴,詳見喵神博客(https://onevcat.com/2016/08/notification/)
開發(fā)者可以拿到更詳細(xì)的app通知設(shè)置,即UNNotificationSettings浇衬,其屬性與設(shè)置里的對(duì)應(yīng)關(guān)系如圖
明確的一一對(duì)應(yīng):authorizationStatus是總開關(guān)径玖,
當(dāng)authorizationStatus是0(notDetermined)時(shí),其他的setting都是0(none或者notSupported)
當(dāng)authorizationStatus是1(denied)時(shí)梳星,其他的setting都是1(disabled)
當(dāng)authorizationStatus是2(authorized)時(shí)冤灾,其他的setting的值就是UI上開關(guān)設(shè)置的值
就這么簡(jiǎn)單!
(天真的我原來居然想當(dāng)然的以為notificationCenterSetting才是開關(guān)是否打開的屬性匿垄,authorizationStatus只是是否授權(quán)的狀態(tài)归粉。。届榄。真是很傻很天真)
iOS8和iOS9更簡(jiǎn)單倔喂,就是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 == []
來判斷是否開了通知是不準(zhǔn)確的班缰,因?yàn)橛脩羝鋵?shí)是可以打開推送開關(guān)悼枢,然后把所有的設(shè)置類型都設(shè)置為關(guān)。给梅。双揪。當(dāng)然你說這種跟關(guān)了總開關(guān)一樣,這就看怎么定義了运吓,用戶已經(jīng)聰明到通過這種方式來避免被推送提醒煩了(會(huì)這么做的應(yīng)該也是程序猿吧?)谋梭,app還提示沒打開推送倦青,那就只能卸載才能不被煩了吧!