iOS - 判断用户是否允许推送通知(iOS7/iOS8)
(iOS8中用戶開啟的推送通知類型對應的是UIUserNotificationType(下邊代碼中UIUserNotificationSettings的types屬性的類型),iOS7對應的是UIRemoteNotificationType)
?
此處以iOS8的UIUserNotificationType為例,(如下圖)當本地通知或push/遠程通知 推送時,這個常量表明了app將通過哪些方式提醒用戶(比如:Badge,Sound,Alert的組合)
那么如何獲得呢,在iOS8中是通過types屬性,[[UIApplication sharedApplication] currentUserNotificationSettings].types
如上圖,獲得之后,我們要知道的是這個property儲存了所有你指定的推送類型(Badge,Sound,Alert),而在圖一中我們知道了推送類型對應的bitmask:(以四位二進制為例)
? ?UIUserNotificationTypeNone? ? = 0, ? ? ? ? ? ? == 0000 ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 0
?? UIUserNotificationTypeBadge ? = 1 << 0, ? ? == 0001 ? ? ?1左移0位 ? ? 2^0 = 1
?? UIUserNotificationTypeSound ? = 1 << 1, ? ? == 0010 ? ? ?1左移1位 ? ? 2^1 = 2?
?? UIUserNotificationTypeAlert ? = 1 << 2, ??== 0100 ? ? ?1左移2位 ? ?2^2 = 4
(以前老師教c語言的時候說過,還可以把左移當做乘2,右移除2)
假如用戶勾選推送時顯示badge和提示sound,那么types的值就是3(1+2) == ?0001 | 0010 = ?0011 ? ?== ?2^0 + 2 ^1 = 3 ?
所以,如果用戶沒有允許推送,types的值必定為0(否則用戶開啟了推送的任何一種類型,進行|按位或操作后,都必定大于0)
1 /** 2 * check if user allow local notification of system setting 3 * 4 * @return YES-allowed,otherwise,NO. 5 */ 6 + (BOOL)isAllowedNotification { 7 //iOS8 check if user allow notification 8 if ([UIDevice isSystemVersioniOS8]) {// system is iOS8 9 UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings]; 10 if (UIUserNotificationTypeNone != setting.types) { 11 return YES; 12 } 13 } else {//iOS7 14 UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes]; 15 if(UIRemoteNotificationTypeNone != type) 16 return YES; 17 } 18 19 return NO; 20 }下面這個方法我是添加在UIDecive的Category中的,用于判斷當前系統版本是大于iOS8還是小于iOS8的
1 /** 2 * check if the system version is iOS8 3 * 4 * @return YES-is iOS8,otherwise,below iOS8 5 */ 6 + (BOOL)isSystemVersioniOS8 { 7 //check systemVerson of device 8 UIDevice *device = [UIDevice currentDevice]; 9 float sysVersion = [device.systemVersion floatValue]; 10 11 if (sysVersion >= 8.0f) { 12 return YES; 13 } 14 return NO; 15 }?
轉載于:https://www.cnblogs.com/fu4904/p/4475015.html
總結
以上是生活随笔為你收集整理的iOS - 判断用户是否允许推送通知(iOS7/iOS8)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: zepto源码研究 - ajax.js(
- 下一篇: 又一款代替PanDownload的百度网