一學就會的極光推送iOS

一.瞭解推送

首先,經過一張圖瞭解極光都作了什麼web


對,咱們經過使用它的推送組件,完成 在線推送遠程推送 工做。bash

平常開發中,推送方式分爲三種:服務器

  • 本地推送

        不經過服務器和網絡,而是經過系統通知中心推送的一種方式網絡

  • 遠程推送

        經過APNs推送服務器,在通知中心和鎖屏欄顯示
app

  • 在線推送

        經過長連接爲應用內推送,和iOS本來的通知體系沒有關係。less


二.證書設置和建立應用

步驟1:Certificates,IDs&Profiles

開啓Push Notification功能


生成推送證書,會獲得一個aos.cer文件


生成描述文件Profile

能夠根據推送場景,選擇發展和發佈文件ide


步驟2:Xcode設置

替換爲推送準備的配置信息fetch

開啓Push Notificationui

檢查bundleID是否與極光應用中的一致this


步驟3:推送應用後臺

建立應用,設置鑑權,打通推送和應用之間的通道

一旦配置好鑑權信息,只能是相同的bundleID,不能更改。須要更改bundleID須要聯繫極光人員進行替換


兩種鑑權方式:

  • 經過導入p12推送證書鑑權

    因爲生產證書也能夠調試,因此能夠直接導入生產證書,不須要導入調試證書,避免二次導入的重複操做

  • 經過keys->auth key受權key來鑑權

    選擇key中的APNs服務,auth key在生產和開發環境能夠通用,因爲不會過時,因此只能下載一次,須要填寫bundleID和teamID


三.集成

APNs通知消息

初始化

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self initloadAPNs];
    return YES;
}

- (void)initloadAPNs {
    //Required
//notice: 3.0.0 及之後版本註冊能夠這樣寫,也能夠繼續用以前的註冊方式
JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound|JPAuthorizationOptionProvidesAppNotificationSettings;

if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
    // 能夠添加自定義 categories
    // NSSet<UNNotificationCategory *> *categories for iOS10 or later
    // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
}
[JPUSHService registerForRemoteNotificationConfig:entity delegate:self];//<JPUSHRegisterDelegate>//協議
}複製代碼

註冊

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
  /// Required - 註冊 DeviceToken
  [JPUSHService registerDeviceToken:deviceToken];
}複製代碼

註冊失敗回調

#pragma mark - 註冊APNs失敗接口
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}複製代碼

控制檯輸出狀態,以下表示接入成功

JGPush[569:185430]  | JIGUANG | I - [JIGUANGDeviceTokenReport] upload device token success複製代碼

獲取APNs推送內容

//獲取APNs內容回調(iOS7-iOS10)
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
     NSLog(@"this is iOS7 Remote Notification");
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
//獲取APNs內容回調(iOS6及如下)
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

    // 取得 APNs 標準信息內容
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    NSString *content = [aps valueForKey:@"alert"]; //推送顯示的內容
    NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //badge 數量
    NSString *sound = [aps valueForKey:@"sound"]; //播放的聲音
    
    // 取得 Extras 字段內容
    NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"]; //服務端中 Extras 字段,key 是本身定義的
    NSLog(@"content =[%@], badge=[%d], sound=[%@], customize field =[%@]",content,badge,sound,customizeField1);
    
    // Required, For systems with less than or equal to iOS 6
    [JPUSHService handleRemoteNotification:userInfo];
}
#pragma mark - 獲取APNs內容 (iOS10以上)
//收到通知還,沒在前面臺展現
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
        }else {
            //本地通知
        }
    } else {
        // Fallback on earlier versions
    }
    if (@available(iOS 10.0, *)) {
        completionHandler(UNNotificationPresentationOptionAlert);// 須要執行這個方法,選擇是否提醒用戶,有 Badge、Sound、Alert 三種類型能夠選擇設置
    } else {
        // Fallback on earlier versions
    }
}
//收到通知,通知已經在前臺展現
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if (@available(iOS 10.0, *)) {
        if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            [JPUSHService handleRemoteNotification:userInfo];
        }else {
            //本地通知
        }
    } else {
        // Fallback on earlier versions
    }
    completionHandler();  // 系統要求執行這個方法
}
#pragma mark- JPUSHRegisterDelegate
//獲取APNs內容(iOS12及以上)
// iOS 12 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
    
    if (@available(iOS 10.0, *)) {
        if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
            //從通知界面直接進入應用
        }else{
            //從通知設置界面進入應用
        }
    } else {
        // Fallback on earlier versions
    }
}複製代碼

注:獲取推送內容的另外一種方法

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // apn 內容獲取:
    //若是爲nil表示不是從通知進來的,若是有值表示從通知進來的
    NSDictionary *remoteNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
    return YES;
}複製代碼

JPush自定義消息

初始化和註冊

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self initloadJPush];
    return YES;
}
appKey選擇 Web Portal 上 的應用 ,點擊「設置」獲取其 appkey 值。請確保應用內配置的 appkey 與 Portal 上建立應用後生成的 appkey 一致。channel指明應用程序包的下載渠道,爲方便分渠道統計,具體值由你自行定義,如:App Store。apsForProduction1.3.1 版本新增,用於標識當前應用所使用的 APNs 證書環境。0(默認值)表示採用的是開發證書,1 表示採用生產證書發佈應用。注:此字段的值要與 Build Settings的Code Signing 配置的證書環境一致。advertisingIdentifier詳見關於 IDFA。- (void)initloadJPush {
    // Required
    //啓動SDK
    [JPUSHService setupWithOption:launchOptions appKey:appkey channel:channel apsForProduction:isProduction];
    
    // Optional
    // 獲取 IDFA
    // 如需使用 IDFA 功能請添加此代碼並在初始化方法的 advertisingIdentifier 參數中填寫對應值
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    //啓動SDK,含IDFA方法
    [JPUSHService setupWithOption:launchOptions appKey:appkey channel:channel apsForProduction:isProduction advertisingIdentifier:advertisingId];
}複製代碼

控制檯輸出狀態,以下表示成功

JGPush[562:182045]  | JIGUANG | I - [JIGUANGLogin] 
----- login result -----
uid:5460310207 
registrationID:171976fa8a8620a14a4 
idc:0複製代碼

獲取自定義推送內容

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *) launchOptions{
    //註冊通知
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    return YES;
}
//實現回調
- (void)networkDidReceiveMessage:(NSNotification *)notification {
   NSDictionary * userInfo = [notification userInfo];
   NSString *content = [userInfo valueForKey:@"content"];
   NSString *messageID = [userInfo valueForKey:@"_j_msgid"];
   NSDictionary *extras = [userInfo valueForKey:@"extras"]; 
   NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服務端傳遞的 Extras 附加字段,key 是本身定義的  
}複製代碼

取消角標操做

除了清除本地角標操做
還能夠操做推送服務器的badge值

- (void)applicationWillEnterForeground:(UIApplication *)application {
    //程序進入前臺,取消App右上角消息數量
    application.applicationIconBadgeNumber = 0;
}複製代碼


四.開發和生產環境調試

推送方式分爲 web JPush 和 App Service,這裏只介紹極光開發者平臺的推送。

極光推送包含的推送手段分爲 發送通知 和 自定義消息。

發送通知(APNs通知)— 在App前臺後臺,退出狀態下均可以,觸發推送通知能夠開啓App
自定義消息(JPush)— 只在應用內推送,也就是要收到推送消息必須保證App在前臺


五.iOS12推送新特性

新增長了自動分組,根據App應用的bundle ID進行推送分組

Thresd identifier對一個App的推送不一樣內容分組

分組摘要主要對分組欄的最下面一行的顯示內容設置格式,默認:還有n個通知


六.定製推送

地理圍欄

用途:在多條件推送的時候,選擇一個地理圍欄,當手機進入或者離開某個區域的時候,會收到推送通知。
遵循協議<JPUSHGeofenceDelegate>注入地理圍欄方法
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [JPUSHService registerLbsGeofenceDelegate:self withLaunchOptions:launchOptions]; 
}
//注入成功後,須要調用協議中的代理方法,才能實現回調後的事件響應複製代碼

用來獲取標籤和別名

用途:在多條件推送的時候,選擇對不一樣的目標人羣,推送不一樣內容。

alias:標識惟一用戶,能夠跟登錄用戶id綁定,保證同應用登錄不一樣帳戶能夠惟一推送。

tag:對用戶人羣,類型標籤,統一推送。如性別,年齡,愛好。

registrationID:JPush註冊成功後會生成一個registrationid,用來表示設備的惟一標識,在指定推送中,能夠根據用戶的惟一標識來推送內容。

//獲取registrationID標籤
[JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {    
    NSLog(@"resCode : %d,registrationID: %@",resCode,registrationID);
}];複製代碼


以上內容純屬我的分享,但願對iOS社區能有更多貢獻。

相關文章
相關標籤/搜索