iOS - 判斷用戶是否容許推送通知(iOS7/iOS8)

(iOS8中用戶開啓的推送通知類型對應的是UIUserNotificationType(下邊代碼中UIUserNotificationSettings的types屬性的類型),iOS7對應的是UIRemoteNotificationType)app

 

此處以iOS8的UIUserNotificationType爲例,(以下圖)當本地通知或push/遠程通知 推送時,這個常量代表了app將經過哪些方式提醒用戶(好比:Badge,Sound,Alert的組合)spa

那麼如何得到呢,在iOS8中是經過types屬性,[[UIApplication sharedApplication] currentUserNotificationSettings].typescode

如上圖,得到以後,咱們要知道的是這個property儲存了全部你指定的推送類型(Badge,Sound,Alert),而在圖一中咱們知道了推送類型對應的bitmask:(以四位二進制爲例)blog

   UIUserNotificationTypeNone    = 0,               == 0000                                 0ci

   UIUserNotificationTypeBadge   = 1 << 0,      == 0001      1左移0位     2^0 = 1it

   UIUserNotificationTypeSound   = 1 << 1,      == 0010      1左移1位     2^1 = 2 io

   UIUserNotificationTypeAlert   = 1 << 2,       == 0100      1左移2位    2^2 = 4class

(之前老師教c語言的時候說過,還能夠把左移當作乘2,右移除2)二進制

假如用戶勾選推送時顯示badge和提示sound,那麼types的值就是3(1+2) ==  0001 | 0010 =  0011    ==  2^0 + 2 ^1 = 3  float

因此,若是用戶沒有容許推送,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 }
相關文章
相關標籤/搜索