iOS技術點:判斷使用者是否開啟推送開關/是否允許推送?,ios開關
- (BOOL)isAllowedNotification {
//iOS8 check if user allow notification
if (IS_IOS_8) {// system is iOS8
UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
if (UIUserNotificationTypeNone != setting.types) {
return YES;
}
} else {//iOS7
UIRemoteNotificationType type = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
if(UIRemoteNotificationTypeNone != type)
return YES;
}
return NO;}
(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