歡迎光臨
每天分享高質量文章

iOS 推送通知

作者:IIronMan
連結:https://www.jianshu.com/p/027120ca9179

總體內容

1、推送通知的介紹

2、本地通知

3、遠端通知

4、極光推送的使用

一、推送通知的介紹

1.1、推送通知的作用:讓不在前臺(後臺或者關閉)的APP知道APP內部發生的事情,效果如下

推送通知的效果

 

提示:這裡說的推送通知跟 NSNotification 有所區別

NSNotification 是抽象的,不可見的

推送通知是可見的(能用肉眼看到)

 

1.2、通知的分類

 

(1)、本地通知

  • 概念:由APP本身給應用程式推送訊息,不需要伺服器的支援

  • 常見場景:記賬軟體定時提醒記賬/番茄工作法中提醒你時間等等

  • 註意:不是非常常用.

 

(2)、遠端通知

  • 概念:由伺服器推送訊息給使用者,需要伺服器的支援

  • 常見場景:微信提醒新訊息/淘寶提醒有新活動/影片軟體提供您有最新電影

  • 註意:非常常用.但是如果僅僅是給使用者提醒,客戶端(你)做的事情就非常簡單.

 

1.3、推送通知的呈現樣式

 

(1)、在螢幕頂部顯示一塊橫幅

在螢幕頂部顯示一塊橫幅

 

(2)、鎖屏介面也可以顯示

鎖屏介面也可以顯示

 

提示:收到通知還可以做如下操作

收到通知時,同時播放音效.(比如支付寶或者微信收賬語音提示)

收到通知時,改變APP圖示上的數字(app圖示上的訊息數量)

二、本地通知(不經常用),demo

https://gitee.com/JKWC/JKLocalNotification.git

 

2.1、本地通知的介紹

 

  • 直接由應用程式(程式中寫入對應程式碼)給使用者發出通知

  • 本地通知需要用到一個重要的類: UILocalNotification

  • 本地通知的實現步驟:

 

(1)、建立本地通知

(2)、設定本地通知要發出的內容等資訊

發出時間

發出內

播放的音效

(3)、排程本地通知

 

2.2、實現本地通知

 

(1)、註冊通知

 

  • iOS8 之後,如果想要發出通知(無論本地還是遠端),必須先進行註冊.(iOS8之前不需要)

  • 通常是在 AppDelegate的didFinishLaunchingWithOptions 中進行註冊,程式碼如下

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

       if (@available(iOS 10.0, *)) {

            //iOS10
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            center.delegate = self;
            [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
           
            }];

        }else{
            /**
                // 不設定型別
                UIUserNotificationTypeNone    = 0,
                // 訊息數量
                UIUserNotificationTypeBadge   = 1 << 0,
                // 聲音
                UIUserNotificationTypeSound   = 1 << 1,
                // 彈出通知
                UIUserNotificationTypeAlert   = 1 << 2,
             */
             UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
             [application registerUserNotificationSettings:notificationSettings];
         }    
    return YES;
}

提示:UIUserNotificationSettings 在iOS10被廢棄了,蘋果推新的 UNUserNotificationCenter,使用UNUserNotificationCenter需要匯入#import,掛代理

 

(2)、建立並且發出通知

 

  • 使用 UIUserNotificationSettings(iOS 8.0~

 

if (@available(iOS 10.0, *)) {

     // 訊息標識
     NSString *identifier = @"request1";
     // 獲取通知中心用來啟用新建的通知
     UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
     // 通知的內容
     UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
     content.badge = [NSNumber numberWithInt:1];
     content.title = @"測試";
     content.body = @"幹嘛呢";
     content.sound = [UNNotificationSound defaultSound];
     // 間隔多久推送一次

     //UNTimeIntervalNotificationTrigger   延時推送
     //UNCalendarNotificationTrigger       定時推送
     //UNLocationNotificationTrigger       位置變化推送

     // 當前時間之後的10s後推送一次(如果重覆的話時間要大於等於60s)
     UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];
     // 定時推送
     //NSDateComponents *dateCom = [[NSDateComponents alloc] init];
     // 每天下午3點10分推送
     // dateCom.hour = 15;
     // dateCom.minute = 10;
     // UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateCom repeats:YES];

     // 建立通知請求
     UNNotificationRequest *notificationRequest = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
     // 將建立的通知請求新增到通知中心
     [center addNotificationRequest:notificationRequest withCompletionHandler:^(NSError * _Nullable error) {

         if (error) {
               NSLog(@"%@本地推送 🙁 報錯 %@",identifier,error);
         }else{
               NSLog(@"通知請求新增到通知中心 Success");
         } 
     }];
} else {

     // 1.建立本地通知
     UILocalNotification *localNotification = [[UILocalNotification alloc]init];

     // 2.設定通知顯示的內容
     // 2.1、設定通知彈出的時間
     localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:6];
     // 2.2、設定通知中心的標題
     localNotification.alertTitle = @"測試";
     // 2.3、設定提示資訊
     localNotification.alertBody = @"幹嘛呢";
     // 2.4、設定滑塊顯示的文字
     localNotification.alertAction = @"快點";
     // 2.5、設定通知的聲音
     // 自定義聲音
     // localNotification.soundName = @"buyao.wav";
     // 系統預設聲音
     localNotification.soundName = UILocalNotificationDefaultSoundName;
     // 2.6、設定應用程式圖示右上角的數字
     localNotification.applicationIconBadgeNumber = 1;

     // 3、排程本地通知(排程之後某個時刻會彈出通知)
     [[UIApplication sharedApplication]scheduleLocalNotification:localNotification];
}

提示:總體屬性展示

// 設定通知彈出的時間

@property(nullable, nonatomic,copy) NSDate *fireDate;

// 時區,預設系統使用的時區

@property(nullable, nonatomic,copy) NSTimeZone *timeZone;

// 通知的重覆間隔

@property(nonatomic) NSCalendarUnit repeatInterval;

// 重覆日期

@property(nullable, nonatomic,copy) NSCalendar *repeatCalendar;

// 區域:當進入該區域時,就會發出一個通知

@property(nullable, nonatomic,copy) CLRegion *region NS_AVAILABLE_IOS(8_0);

// YES:進入某一個時區只會發出一次通知,NO:每次進入該區域都會發出通知

@property(nonatomic,assign) BOOL regionTriggersOnce NS_AVAILABLE_IOS(8_0);

// 提示資訊

@property(nullable, nonatomic,copy) NSString *alertBody;

// 用於決定 alertAction 是否生效

@property(nonatomic) BOOL hasAction;

// 鎖屏介面滑塊下顯示的文字

@property(nullable, nonatomic,copy) NSString *alertAction;

// 不需要設定

@property(nullable, nonatomic,copy) NSString *alertLaunchImage;

// 通知中心的標題

@property(nullable, nonatomic,copy) NSString *alertTitle NS_AVAILABLE_IOS(8_2);

// 設定通知發出時音效

@property(nullable, nonatomic,copy) NSString *soundName;

// 應用程式右上角的數字

@property(nonatomic) NSInteger applicationIconBadgeNumber;

// 額外資訊

@property(nullable, nonatomic,copy) NSDictionary *userInfo;

(3)、移除通知

 

// 移除所有的通知
[[UIApplication sharedApplication] cancelAllLocalNotifications];

// 移除某個通知
// [[UIApplication sharedApplication] cancelLocalNotification:@"某個通知物件"];

提示:如果在iOS 10之後 UNUserNotificationCenter 可以如下移除通知, requestID 是識別符號

[center removePendingNotificationRequestsWithIdentifiers:@[requestID]];
[center removeAllDeliveredNotifications];

2.3、監聽本地通知的點選

 

(1)、為什麼要監聽本地通知的點選?

  • 通知點選之後會發生什麼事情?

  • 不管應用程式出於後臺還是被殺死,點選通知都可以開啟應用程式

  • 什麼情況下需要監聽使用者點選了通知(不常用)

  • 比如:當用點選通知時,進入到某一個固定介面

 

(2)、監聽本地通知的點選,應用程式分很多種狀態

  • 在前臺:如果在前臺不需要進行頁面跳轉

  • 在後臺:點選應用時進行頁面的跳轉

  • 被殺死:點選應用開啟應用時,進行頁面的跳轉

 

應用程式在前臺或者後臺時的程式碼如下

 

// 應用在前臺時,也會收到該通知,這時不應該進行頁面的跳轉
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{

     NSLog(@"本地通知的點選");
     /**
        UIApplicationStateActive, 前臺
        UIApplicationStateInactive, 進入前臺
        UIApplicationStateBackground 在後臺
      */
     if (application.applicationState == UIApplicationStateActive)
     return; // 前臺情況下 不做操作

     // 進行頁面的跳轉
}

應用程式被殺死時的情況下不會走上面的程式碼,但是不管是在任何情況下都會走下麵的程式碼,透過launchOptions的key來做出各種判斷,程式碼如下

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

      if (@available(iOS 10.0, *)) {

         //iOS10
         UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
         center.delegate = self;
         [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) 
         {
          
         }];
       }else{
         UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
         [application registerUserNotificationSettings:notificationSettings];
       }
      // 判斷是否是透過點選通知開啟了應用程式
      if (launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]) {
          // 在app殺死的情況下,本地通知的所走的地方
      }
   return YES;
}

提示:對應 launchOptions 的其他常用 key 如下

  • 對應的是啟動應用程式的的遠端通知資訊userInfo(NSDictionary)

    UIApplicationLaunchOptionsRemoteNotificationKey

  • 對應的是為啟動應用程式的的本地通知物件(UILocalNotification)

    UIApplicationLaunchOptionsLocalNotificationKey

  • 對應的物件為啟動URL(NSURL)

    UIApplicationLaunchOptionsURLKey

  • 從點選3D Touch iCon啟動,對應的是點選的iCon的資訊。

    UIApplicationLaunchOptionsShortcutItemKey

  • 有關藍芽的操作

    UIApplicationLaunchOptionsBluetoothPeripheralsKey

    UIApplicationLaunchOptionsBluetoothCentralsKey

  • 對應啟動的源應用程式的bundle ID (NSString)

    UIApplicationLaunchOptionsSourceApplicationKey

三、遠端通知,demo

3.1、什麼是遠端通知 ?

 

  • 概念:由伺服器傳送訊息給使用者彈出訊息的通知(需要聯網)

  • 遠端推送服務,又稱為 APNs(Apple Push Notification Services)

  • APNs 通知:是指透過向 Apple APNs 伺服器傳送通知,到達 iOS 裝置,由 iOS 系統提供展現的推送。使用者可以透過 IOS 系統的 “設定” >> “通知” 進行設定,開啟或者關閉某一個 App 的推送能力。

 

3.2、為什麼需要遠端通知 ?

 

  • 例子:京東 搞活動,促銷活動或者商品降價,想告知使用者.但是該使用者不經常開啟京東APP.京東如何通知該使用者有最新的活動呢?

  • 傳統方式:只有使用者開啟了京東客戶端,客戶端向伺服器請求是否有最新的活動,才能在APP中告知使用者活動.

  • 侷限性:只要使用者關閉了app,就無法跟app的伺服器溝通,無法從伺服器上獲得最新的資料內容

  • 遠端通知的好處:不管使用者開啟還是關閉app,只要聯網了,都能接收到伺服器推送的遠端通知

 

3.3、遠端通知的原理

 

(1)、原理圖

遠端通知的原理圖

 

(2)、為什麼京東伺服器不直接推訊息給使用者?

 

  • 在通常情況下伺服器端是不能主動向客戶端推訊息的.

  • 如果想伺服器端給客戶端推訊息,必須建立長連線

  • 京東客戶端在處於後臺時(app殺死的情況下)不能和伺服器端建立長連線

 

(3)、為什麼蘋果伺服器可以推訊息給使用者?

 

所有的蘋果裝置,在聯網狀態下,都會與蘋果的伺服器建立長連線

蘋果建立長連線的作用: 時間校準、系統升級提示、查詢我的iPhone、遠端通知 等等

常見疑惑:蘋果在推送訊息時,如何準確的推送給某一個使用者,並且知道是哪一個APP ?

在京東伺服器把訊息給蘋果的APNs伺服器時,必須告知蘋果DeviceToken

 

什麼是 DeviceToken ?

 

  • DeviceToken是由使用者手機的UDID和應用程式的BundleID共同生成的

  • 透過DeviceToken可以找到唯一手機中的唯一應用程式

 

如何獲得DeviceToken:客戶端到蘋果的APNs註冊即可獲得。

 

(4)、完整的流程圖

遠端推送完整的流程圖

 

3.4、如何做遠端通知 ?

 

首先,BundleID對應的App ID必須是明確的(特殊功能)

 

該APPID必須配置兩個證書

 

  • 開發證書:用於除錯遠端推送

  • 釋出證書:用於釋出後給使用者推送訊息

 

根據上面的App ID重新配置描述檔案

 

安裝對應的證書,即可開始測試遠端推送

 

3.5、遠端通知證書配置

 

(1)、我們先建立一個 CSR 檔案(又叫做:證書簽名請求檔案)(下麵會用到,它是用來系結電腦的)

 

找到 Launchpad 裡面的 鑰匙串訪問

鑰匙串訪問

 

開啟鑰匙串訪問->證書助理->從證書機構頒請求證書

 

出現如下介面,選擇儲存到磁碟,點選繼續

 

選擇儲存到待會好找的地方(比如:桌面,自己建的檔案夾等等),儲存

 

(2)、在 Identifiers裡面建立一個明確的App ID,如下

提示:Bundle ID 一定要填寫明確的

 

(3)、為(2)中建立的App ID 配置推送 開發證書(測試證書)與推送釋出證書

 

配置推送 **開發證書**(測試證書)與推送**釋出證書**

點選上圖的Edit之後滾動到下麵

選擇我們上面建立的CSR檔案

 

下載開發推送證書

提示:推送釋出的證書也一樣:點選 Create Certificate->選擇 CSR 檔案->下載釋出推送證書

開發證書和釋出證書

配置成功後的效果

(4)、配置描述檔案

 

iOS證書分2種,1種是開發證書,用來給你(開發人員)做真機測試的;1種是釋出證書,釋出證書又分釋出到app store的(這裡不提及)和釋出測試的ad hoc證書。

 

 

配置描述檔案分類

 

在此我們僅僅建立 iOS App Development 來進行測試遠端推送

 

下載下來描述檔案

  • 提示:描述檔案下載完後記得雙擊執行一下

 

3.6、獲取遠端推送要用的 DeviceToken

 

(1)、工程的 Bundle identifier 要與我們上面設定的 App ID 保持一致,並且開啟下麵的選項

 

(2)、在蘋果的APNs伺服器註冊,以獲取DeviceToken

 

通常在 AppDelegate 裡面的 didFinishLaunchingWithOptions 中新增如下程式碼進行註冊

 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

  if ([UIDevice currentDevice].systemVersion.doubleValue <= 8.0) {

      /**
         向伺服器發請求,要註冊推送功能,以此獲取到伺服器傳回的deviceToken
         type 用來說明 支援的通知形式
         如 橫幅 聲音  角標
       */
       [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert];

   }else{

       if (@available(iOS 10.0, *)) {
            //iOS10
            // 1.向用戶請求可以給使用者推送訊息
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            center.delegate = self;
            [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            
            }];
       }else{

            // 1.向用戶請求可以給使用者推送訊息
            UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
            [application registerUserNotificationSettings:notificationSettings];

       }

       // 2.註冊遠端通知(拿到使用者的DeviceToken)
       [application registerForRemoteNotifications];
   }

   return YES;
}

註冊之後在另外一個代理方法中,拿到DeviceToken

 

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
   // 將使用者的使用者名稱和deviceToken傳送給伺服器,讓伺服器進行儲存備份即可
   NSLog(@"%@", deviceToken);   
   // 例如:
   // 其中我們伺服器要儲存的 deviceToken 是不包括兩邊的尖括號的
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
   NSLog(@"%@", error.userInfo);
}

提示:

  • 獲取到的 deviceToken 傳送給伺服器,讓伺服器進行儲存備份即可

  • 我們伺服器要儲存的 deviceToken 是不包括兩邊的尖括號的

 

3.7、測試方式一: 遠端通知

 

(1)、使用一個第三方的Mac程式來測試:PushMeBaby,並刪除裡面的資源,把我們自己推送的開發證書與釋出證書模仿其命名改名並拖進去

修改後的工程

 

(2)、修改 PushMeBaby裡面的ApplicationDelegate.m,把 self.deviceToken 修改為我們上面 3.6 中執行後拿到的 DeviceToken,切記 DeviceToken 不包含左右尖括號

修改內容

 

(3)、做完面操作,執行PushMeBaby,選擇相應的內容

進行選擇

 

執行後的效果

3.8、測試方式二:使用SmartPush可以在電腦上方便的模擬APNs推送。執行程式,選擇我們生成的證書和填上列印欄獲得的DeviceToken,就能在我們的App中看到APNs推送來的帶有3DTouch功能的通知。

SmartPush

提示:推送的效果和上面的一樣,但是體驗更好,建議測試使用 SmartPush

3.9、監聽遠端通知的點選事件,其實和本地通知的監聽是一樣的,一種是在前臺和後臺的監聽,一種是在app殺死情況下的監聽,程式碼如下

 

#import "AppDelegate.h"
#import 
@interface AppDelegate ()<UNUserNotificationCenterDelegate>

@end
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    if ([UIDevice currentDevice].systemVersion.doubleValue <= 8.0) {
  
        //向伺服器發請求,要註冊推送功能,以此獲取到伺服器傳回的deviceToken
        //type 用來說明 支援的通知形式
        //如 橫幅 聲音  角標
        [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound|UIRemoteNotificationTypeAlert];
     }else{
           if (@available(iOS 10.0, *)) {
                 //iOS10
                 // 1.向用戶請求可以給使用者推送訊息
                 UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
                 center.delegate = self;
                 [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
                 
                 }];
             }else{
                 // 1.向用戶請求可以給使用者推送訊息
                 UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
                 [application registerUserNotificationSettings:notificationSettings];
             }
  
         // 2.註冊遠端通知(拿到使用者的DeviceToken)
         [application registerForRemoteNotifications]; 
     }
     // 判斷是否是透過點選通知開啟了應用程式
     if (launchOptions[UIApplicationLaunchOptionsRemoteNotificationKey]) {
           // 遠端通知的監聽
     }
   return YES;
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
     // 將使用者的使用者名稱和deviceToken傳送給伺服器,讓伺服器進行儲存備份即可
     NSLog(@"%@", deviceToken);
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{  
     NSLog(@"%@", error);  
}

#pragma mark 使用者在後臺狀態或者前臺狀態收到遠端通知的方法
-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{

     NSLog(@"收到遠端通知");
     // 應用在前臺時,也會收到該通知,這時不應該進行頁面的跳轉
     /**
       UIApplicationStateActive, 前臺
       UIApplicationStateInactive, 進入前臺
       UIApplicationStateBackground 在後臺
      */
      if (application.applicationState == UIApplicationStateActive)
      return; // 前臺情況下 不做操作

      // 進行頁面的跳轉

}
@end

提示:我們可以使用新的監聽使用者點選遠端通知的方法,如下:(包含上面的兩種監聽方式)

 

/*
  此方法是新的用於響應遠端推送通知的方法
  1.如果應用程式在後臺,則通知到,點選檢視,該方法自動執行
  2.如果應用程式在前臺,則通知到,該方法自動執行
  3.如果應用程式被關閉,則通知到,點選檢視,先執行didFinish方法,再執行該方法
  4.可以開啟後臺掃清資料的功能
    step1:點選target-->Capabilities-->Background Modes-->Remote Notification勾上
    step2:在給APNs伺服器傳送的要推送的資訊中,新增一組字串如:
    {"aps":{"content-available":"999","alert":"bbbbb.","badge":1}}
    其中content-availabel就是為了配合後臺掃清而新增的內容,999可以隨意定義
*/
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
     // 前臺情況下 不做操作
     if (application.applicationState == UIApplicationStateActive)
     return; 
    
     //NewData就是使用新的資料 更新介面,響應點選通知這個動作
     completionHandler(UIBackgroundFetchResultNewData);
}

其中 content-availabel 就是為了配合後臺掃清而新增的內容,999可以隨意定義

四、極光推送 的使用,demo

4.1、極光推送 iOS 檔案

 

  • APNs 通知:是指透過向 Apple APNs 伺服器傳送通知,到達 iOS 裝置,由 iOS 系統提供展現的推送。使用者可以透過 IOS 系統的 “設定” >> “通知” 進行設定,開啟或者關閉某一個 App 的推送能力。

  • JPush iOS SDK 不負責 APNs 通知的展現,只是向 JPush 伺服器端上傳 Device Token 資訊,JPush 伺服器端代理開發者向 Apple APNs 推送通知。

  • APNs 通知與應用內訊息對比

 

APNS 應用內訊息
推送原則 由 JPush 伺服器傳送至 APNS 伺服器,再下發到手機。 由 JPush 直接下發,每次推送都會嘗試傳送,如果使用者線上則立即收到。否則儲存為離線。
離線訊息 離線訊息由 APNS 伺服器快取按照 Apple 的邏輯處理。 使用者不線上 JPush server 會儲存離線訊息,時長預設保留一天。離線訊息保留 5 條。
推送與證書環境 應用證書和推送指定的 iOS 環境匹配才可以收到。 自定義訊息與 APNS 證書環境無關。
接收方式 應用退出,後臺以及開啟狀態都能收到 APNS。 需要應用開啟,與 JPush 建立連線才能收到。
展示效果 如果應用後臺或退出,會有系統的 APNS 提醒。如果應用處於開啟狀態,則不展示,iOS 10 開始可實現前臺展示。 非 APNS,預設不展示。可透過獲取介面自行編碼處理。
處理函式 Apple 提供的介面:didReceiveRemoteNotification JPush 提供的介面:networkDidReceiveMessage

JPush APNs 通知的意義

 

OS 平臺上推送通知,只有 APNs 這個官方的通道,是可以隨時送達的。一般開發者都是自己部署應用伺服器向 APNs Server 推送。

 

JPush iOS 推送相比直接向 APNs 推送有什麼好處呢?

 

減少開發及維護成本:

  • 應用開發者不需要去開發維護自己的推送伺服器與 APNs 對接。

  • 集成了 JPush iOS SDK 後不必自己維護更新 device token。

  • 透過 JPush 的 Web Portal 直接推送,也可以呼叫 JPush 的 HTTP 協議 API 來完成,開發工作量大大減少。

 

減少運營成本:

  • 極光推送支援一次推送,同時向 Android, iOS, WinPhone 三個平臺。支援統一的 API 與推送介面。

  • 極光推送提供標簽、別名系結機制,以及提供了非常細分的使用者分群方式,運營起來非常簡單、直觀。

 

提供應用內推送:

  • 除了使得 APNs 推送更簡單,也另外提供應用內訊息推送。這在類似於聊天的場景裡很有必要。

 

4.2、在極光推送平臺建立一個應用

 

 

4.3、iOS SDK 整合,官網講解的很詳細,在此我們就簡單的採用 Cocoapods 匯入 極光推送的iOS SDK

 

透過 Cocoapods 下載地址:

 

pod 'JPush'

提示:如果無法匯入最新版本,請執行 pod repo update master 這個命令來升級本機的 pod 庫,然後重新 pod ‘JPush’

如果需要安裝指定版本則使用以下方式(以 3.1.0 版本為例):

 

pod 'JPush', '3.1.0'

提示:匯入成功後還有一些工程的配置問題大家看官方檔案即可

 

4.4、測試專案的 Bundle Identifier要與我們上面建立證書的 Bundle ID 保持一致,並且開啟如下圖所示

靜默推送的設定

 

靜默推送(silent_push):如果只攜帶content-available: 1,不攜帶任何badge,sound 和訊息內容等引數,則可以不打擾使用者的情況下進行內容更新等操作即為“Silent Remote Notifications”。

 

4.5、在 AppDelegate.m 匯入極光推送的相應程式碼,在此我就不再匯入了,說一下幾個引數,在didFinishLaunchingWithOptions 方法裡面會使用到下麵的引數

appKey:選擇 Web Portal 上 的應用 ,點選“設定”獲取其 appkey 值。請確保應用內配置的 appkey 與 Portal 上建立應用後生成的 appkey 一致。

提示其實也就是我們上面建立應用成功後生成的key

channel:指明應用程式包的下載渠道,為方便分渠道統計,具體值由你自行定義,如:App Store。

 

apsForProduction:1.3.1 版本新增,用於標識當前應用所使用的 APNs 證書環境。

 

0(預設值)表示採用的是開發證書,1 表示採用生產證書釋出應用。

註:此欄位的值要與 Build Settings的Code Signing 配置的證書環境一致。

advertisingIdentifier: 詳見關於 IDFA。

 

在demo裡面我們寫了一個來處理推送是跳轉還是其他操作的方法

 

#pragma mark 對於推送的處理(可以把上面notificationUI的方法替換掉)
- (void)goToMessageViewControllerWithDic:(NSDictionary *)userInfo {

   if ([[userInfo objectForKey:@"go"] isEqualToString:@"update"]) {

       // 應用程式更新
       [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@""]];
       return;
    }

   //將欄位存入本地,因為要在你要跳轉的頁面用它來判斷,這裡我只介紹跳轉一個頁面,
   NSUserDefaults *pushJudge = [NSUserDefaults standardUserDefaults];
   [pushJudge setObject:@"push"forKey:@"push"];
   [pushJudge synchronize];
   // 這個是我要跳到的測試頁面 (你的標的頁面)
   TestViewController *testVC = [[TestViewController alloc]init];
   UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:testVC];//這裡加導航欄是因為我跳轉的頁面帶導航欄,如果跳轉的頁面不帶導航,那這句話請省去。
   [self.window.rootViewController presentViewController:nav animated:YES completion:nil];

}

4.6、在極光推送後臺進行推送,傳送通知

 

傳送通知

 

可選設定 

 

在當我們點選推送後,我們在手機可以收到如下效果

 

在app的 AppDelegate.m 列印推送的內容,如下

在app的 `AppDelegate.m` 列印推送的內容

 

到此,極光推送使用完畢,有興趣還可以看看 個推 的推送

 

推薦本地通知與遠端通知的部落格:

  • iOS開發本地推送(iOS10)UNUserNotificationCenter

    https://www.cnblogs.com/xianfeng-zhang/p/8310394.html

  • 關於使用 UNUserNotificationCenter 的本地通知

    https://www.jianshu.com/p/3260f864e5aa

  • iOS10 本地推送 UNUserNotificationCenter

    https://www.jianshu.com/p/bed37cfe7386

  • iOS10 推送通知詳解(UserNotifications)
    iOS 遠端推送通知

    https://www.cnblogs.com/czq1989/p/5098871.html

  • iOS10以前的本地通知和遠端通知

    https://www.cnblogs.com/yang-shuai/p/9104013.html

贊(0)

分享創造快樂