iOS推送那點事兒

最近由於項目須要,須要研究下推送和webView,由於原來的工程是2012年寫的,代碼編寫規範以及API的使用都已經老掉牙地要入土了。舉個栗子:列表不用tableview寫,而是for循環建立了一堆button,難道是那時候尚未tableview麼...因此這樣的代碼,除了重構,我想不到其餘辦法。web

###我感受我是幸運的,由於當我準備調研推送和webview的時候,蘋果爸爸已經對他們進行觸及靈魂的改造了,我天然能夠靠着大樹乘涼,直接入手iOS新版本的推送和iOS8出道的WKWebview。扯皮了這麼多,是時候展示真正的技術了! --------------------------前方蘭博紅溫預警------------------------ ###本文是iOS推送系列的第一篇,主要講一下實現推送功能以前的準備工做,以及前期的推送註冊,後續將會更新更多關於iOS10推送的新鮮內容。api

iOS10的推送相比較以前的來講,真的能夠用脫胎換骨來形容,新增了UserNotifications Framework,但使用起來其實很簡單。app

##1、戰前準備 1.你必需要有1個development證書,若是要發佈固然還要有一個distribution證書;
2.你必需要打開工程裏的推送開關,不打開則一切皆爲虛空。。。 Push Notificaitons
3.你可能還須要打開Background Modes裏的Romote notification,雖然做者如今還有搞清這東西有軟用,還忘知道的同志留言分享。 Reomote notification
4.閱讀蘋果爸爸給孩子們寫的信---官方文檔,既能提高文檔閱讀能力,還能加深對框架的理解,順便把英語給學了,穩賺不賠的買賣。其實看文檔,寫文檔是一個開發人員行走江湖的必備技能。框架

##2、iOS10先後的推送註冊 ####(附贈兩個三方推送註冊)post

#import <UserNotifications/UserNotifications.h>

/* 判斷機型 */
// 建議宏和一些經常使用參數都添加到項目的config文件中
#define isiOS10                       ([[[UIDevice currentDevice]systemVersion]floatValue] >=  10.0)
#define isiOS7                          ([[[UIDevice currentDevice]systemVersion]floatValue] >= 7.0)
#define isiOS8                          ([[[UIDevice currentDevice]systemVersion]floatValue] >= 8.0)
#define isiOS7_1                        ([[[UIDevice currentDevice]systemVersion]floatValue] >  7.0)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 1.系統通知
    // (1)推送註冊,分爲iOS10以後和以前
    if (isiOS10) {
        // iOS10使用如下方法註冊,才能獲得受權
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        UNAuthorizationOptions types10 = UNAuthorizationOptionBadge | UNAuthorizationOptionAlert | UNAuthorizationOptionSound;
        [center requestAuthorizationWithOptions:types10 completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error) { // 獲取通知受權成功
                NSLog(@"Request UNUserNofication authorization succeeded.");
                if (granted) { // 點擊容許,這裏能夠添加一些本身的邏輯
                    NSLog(@"用戶容許通知");
                } else { // 點擊不容許,這裏能夠添加一些本身的邏輯
                    NSLog(@"用戶不容許通知");
                }
                
                // (2)獲取當前通知,  UNNotificationSetting只是讀對象,不能修改,只能經過如下方法獲取
                [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
                    // 此處查看並設置通知相關信息
                }];
             
                [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
                    if (error) {
                        NSLog(@"Add request of more settings for UNUserNotification error:%@", error);
                    }
                }];
            } else {
                NSLog(@"Request UNUserNofication authorization failed.");
            }
        }];
        
    // 2.UMPush
    // (1)UM推送初始化
    [UMessage startWithAppkey:UMAppKey launchOptions:launchOptions];
    
    // (2)UM通知註冊
    [UMessage registerForRemoteNotifications];
    
    // (3)UM日誌
    [UMessage setLogEnabled:YES];

    // 3.用友有信
    // (1)有信IM相關設置
    [[YYIMChat sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    
    // (2)註冊app
    [[YYIMChat sharedInstance] registerApp:YYAPPIDNew etpKey:@"cidtech"];
    
    // (3)註冊多方通話
    [[YYIMChat sharedInstance].chatManager registerDuduWithAccountIdentify:@"" appkeyTemp:@""];
    
    // (4)添加代理
    [[YYIMChat sharedInstance].chatManager addDelegate:self];
    
    // (5)註冊token代理
    [[YYIMChat sharedInstance].chatManager registerTokenDelegate:self];
    
    // (6)設置日誌級別
    [[YYIMChat sharedInstance] setLogLevel:YYIM_LOG_LEVEL_VERBOSE];
    
    // (7)本地推送
    [[YYIMChat sharedInstance].chatManager setEnableLocalNotification:YES];
    
    // (8)註冊推送證書
#if defined(DEBUG) && DEBUG
    [[YYIMChat sharedInstance] registerApnsCerName:@"你的開發push證書"];
#else
    [[YYIMChat sharedInstance] registerApnsCerName:@"你的生產push證書"];
#endif
    
    // (9)設置高德地圖key,參見高德地圖官網(有信IM內置的發送位置功能須要集成高德地圖API)
    [MAMapServices sharedServices].apiKey = kYYMapKey;
    }
    
/** 獲取deviceToken 存儲本地以及相關注冊 */
- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
    // 1.有信IM推送註冊
    [[YYIMChat sharedInstance] application:application didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
    
    // 2.有盟U-Push推送註冊
    [UMessage registerDeviceToken:deviceToken];
    
    // 3.deviceToken存儲
    NSString *deviceTokenAppend = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
                                    stringByReplacingOccurrencesOfString: @">" withString: @""]
                                   stringByReplacingOccurrencesOfString: @" " withString: @""];
    [[NSUserDefaults standardUserDefaults] setObject:deviceTokenAppend forKey:DEVICETOKEN];
    [[NSUserDefaults standardUserDefaults] synchronize];
    NSLog(@"deviceToken-------%@",deviceTokenAppend);
}

 // iOS10如下系統
    else {
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil];
        [application registerUserNotificationSettings:settings];
    }
}    
    // 遠程推送註冊-必須加的一個方法!
    [[UIApplication sharedApplication] registerForRemoteNotifications];

/** iOS10如下-接收到遠程通知 */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [self.rootVC.tabBarView selectWithIndex:0];
    [self.rootVC selectViewControllerWithIndex:0];
    [[YYIMChat sharedInstance] application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
    [[NSNotificationCenter defaultCenter] postNotificationName:VERIFYNOTIFICATION_REMOTE object:userInfo];
}


/** iOS10如下-接收到本地通知 */
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    [[YYIMChat sharedInstance] application:application didReceiveLocalNotification:notification];
}

// iOS10新增:處理前臺收到通知的代理方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //應用處於前臺時的遠程推送接受
        //關閉友盟自帶的彈出框
        [UMessage setAutoAlert:NO];
        //必須加這句代碼
        [UMessage didReceiveRemoteNotification:userInfo];
        
    } else {
        //應用處於前臺時的本地推送接受
    }
    //當應用處於前臺時提示設置,須要哪一個能夠設置哪個
    completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionAlert);
}

// iOS10新增:處理後臺點擊通知的代理方法
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        // 必須加這句代碼
        [UMessage didReceiveRemoteNotification:userInfo];
        
        // 應用處於後臺時的遠程推送接受
        
    } else {
        // 應用處於後臺時的本地推送接受
    }
}

###以上是iOS10以及以前版本推送和三方推送有盟推送、用友推送的註冊,下面咱們就來看看iOS10推送真正使人驚豔的地方fetch

##3、真正使人激動的功能 iOS10以前的推送是這樣的
輸入圖片說明
iOS10以後的推送是這樣的
輸入圖片說明
還能夠是這樣的
輸入圖片說明
#戛然而止。。。 ###做者會在後面繼續更新新的博客和你們分享、交流,初來乍到,但願獲得你們的批評和指正!代理

相關文章
相關標籤/搜索