iOS SDK 集成指南

最新更新:2022-12-01

適用版本

本文匹配的 MTPush iOS SDK 版本:v3.0.0 及以後版本。

資源文件

包名為 engagelab-ios-{版本號}

注意从4.3.3版本开始,不再提供.a包。都将只提供.xcframework的包。

  • lib 文件夹:包含 mtpush-ios-x.x.x.xcframework,mtpush-extension-ios-x.x.x.xcframework,(请注意:模拟器不支持 APNs)

  • README 文件:SDK 相關說明

  • demo 檔案夾:示例

獲取應用程式資訊

在控製台上創建應用程式,創建成功後自動生成 AppKey 用以標識該應用程式,詳情參考 應用程式設置文檔

配置專案

導入 SDK

Cocoapods 導入

pod 'MTPush' 註:如果無法導入最新版本,請執行 pod repo update master 這個命令來升級本機的 pod 庫,然後重新 pod 'MTPush'
              pod 'MTPush'

    註:如果無法導入最新版本,請執行 pod repo update master 這個命令來升級本機的 pod 庫,然後重新 pod 'MTPush'

        
此代碼塊在浮窗中顯示
  • 如果需要安裝指定版本則使用以下方式(以 MTPush 3.5.0 版本為例):
pod 'MTPush', '3.5.0'
              pod 'MTPush', '3.5.0'

        
此代碼塊在浮窗中顯示

手動導入

  • -將SDK包解壓,在Xcode中選擇“Add files to 'Your project name'…”,將mtpush-ios-x.x.x.xcframework添加到你的工程目錄中。
  • 添加 Framework
    • CFNetwork.framework
    • CoreFoundation.framework
    • CoreTelephony.framework
    • SystemConfiguration.framework
    • CoreGraphics.framework
    • Foundation.framework
    • UIKit.framework
    • Security.framework
    • libz.tbd
    • UserNotifications.framework
    • libresolv.tbd
    • libsqlite3.tbd

Build Settings

如果你的專案需要支持小於 7.0 的 iOS 係統,請到 Build Settings 關閉 bitCode 選項,否則將無法正常編譯通過。

  • 設置 Search Paths 下的 User Header Search Paths 和 Library Search Paths,比如 SDK 檔案夾(預設為 lib )與專案文件在同一級目錄下,則都設置為 "$(SRCROOT)/{靜態庫所在檔案夾名稱}" 即可。

Capabilities

如使用 Xcode 8 及以上環境開發,請開啓 Application Target 的 Capabilities->Push Notifications 選項,如圖: 1.png
如使用 Xcode 10 及以上環境開發,請開啓 Application Target 的 Capabilities-> Access WIFI Infomation 選項。 image.png

添加頭文件

請將以下代碼添加到 AppDelegate.m 引用頭文件的位置。

// 引入 MTPush 功能所需頭文件 #import "MTPushService.h" // iOS10 註冊 APNs 所需頭文件 #ifdef NSFoundationVersionNumber_iOS_9_x_Max #import <UserNotifications/UserNotifications.h> #endif // 如果需要使用 idfa 功能所需要引入的頭文件(可選) #import <AdSupport/AdSupport.h>
          // 引入 MTPush 功能所需頭文件
#import "MTPushService.h"
// iOS10 註冊 APNs 所需頭文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// 如果需要使用 idfa 功能所需要引入的頭文件(可選)
#import <AdSupport/AdSupport.h>

        
此代碼塊在浮窗中顯示

添加 Delegate

為 AppDelegate 添加 Delegate,參考代碼如下:

@interface AppDelegate ()<MTPushRegisterDelegate> @end
          @interface AppDelegate ()<MTPushRegisterDelegate>

@end

        
此代碼塊在浮窗中顯示

添加初始化代碼

添加初始化 APNs 代碼

請將以下代碼添加到 -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

//Required MTPushRegisterEntity * entity = [[MTPushRegisterEntityMTPushRegisterEntity alloc] init]; entity.types = MTPushAuthorizationOptionAlert|MTPushAuthorizationOptionSound|MTPushAuthorizationOptionProvidesAppNotificationSettings; if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) { // 可以添加自訂 categories // NSSet<UNNotificationCategory *> *categories for iOS10 or later // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9 } [MTPushService registerForRemoteNotificationConfig:entity delegate:self];
            //Required
 
  MTPushRegisterEntity * entity = [[MTPushRegisterEntityMTPushRegisterEntity alloc] init];
  entity.types = MTPushAuthorizationOptionAlert|MTPushAuthorizationOptionSound|MTPushAuthorizationOptionProvidesAppNotificationSettings;
  if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
    // 可以添加自訂 categories
    // NSSet<UNNotificationCategory *> *categories for iOS10 or later
    // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
  }
  [MTPushService registerForRemoteNotificationConfig:entity delegate:self];

        
此代碼塊在浮窗中顯示

添加初始化 MTPush 代碼

請將以下代碼添加到 -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

// Optional // 獲取 IDFA // 如需使用 IDFA 功能請添加此代碼並在初始化方法的 advertisingIdentifier 參數中填寫對應值 NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]; // Required // init Push [MTPushService setupWithOption:launchOptions appKey:appKey channel:channel apsForProduction:isProduction advertisingIdentifier:advertisingId];
          // Optional
// 獲取 IDFA
// 如需使用 IDFA 功能請添加此代碼並在初始化方法的 advertisingIdentifier 參數中填寫對應值
NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];

// Required
// init Push
[MTPushService setupWithOption:launchOptions appKey:appKey
                      channel:channel
             apsForProduction:isProduction
        advertisingIdentifier:advertisingId];

        
此代碼塊在浮窗中顯示
部分參數說明
  • appKey
    • 請確保應用程式內配置的 appkey 與 Portal 上創建應用程式後生成的 appkey 一緻。
  • channel
    • 指明應用程式包的下載通路,為方便分通路統計,具體值由你自行定義,如:App Store。
  • apsForProduction
    • 用於標識當前應用程式所使用的 APNs 證書環境。
    • 0(預設值)表示採用的是開發證書,1 表示採用生産證書PO應用程式。
    • 註:此字段的值要與 Build Settings的Code Signing 配置的證書環境一緻。

註冊 APNs 成功並上報 DeviceToken

溫馨提示:如果不調用此方法也可以登入 EngageLab。但是不能使用 APNs 通知功能,隻可以使用 EngageLab 自訂訊息。

請在 AppDelegate.m 實現該回調方法並添加回調方法中的代碼:

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { /// Required - 註冊 DeviceToken [MTPushService registerDeviceToken:deviceToken]; }
          - (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

  /// Required - 註冊 DeviceToken
  [MTPushService registerDeviceToken:deviceToken];
}

        
此代碼塊在浮窗中顯示

實現註冊 APNs 失敗接口(可選)

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { //Optional NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error); [MTPushService registerDeviceToken:deviceToken]; }
          - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
  //Optional
  NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
  [MTPushService registerDeviceToken:deviceToken];
}

        
此代碼塊在浮窗中顯示

添加處理 APNs 通知回調方法

請在 AppDelegate.m 實現該回調方法並添加回調方法中的代碼:

#pragma mark- MTPushRegisterDelegate // iOS 12 Support - (void)mtpNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {// 從通知介面直接進入應用程式}else{// 從通知設置介面進入應用程式} } // iOS 10 Support - (void)mtpNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler { // Required NSDictionary * userInfo = notification.request.content.userInfo; if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {[MTPushService handleRemoteNotification:userInfo]; } completionHandler(UNNotificationPresentationOptionAlert); // 需要執行這個方法,選擇是否提醒用戶,有 Badge、Sound、Alert 三種類型可以選擇設置 } // iOS 10 Support - (void)mtpNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler { // Required NSDictionary * userInfo = response.notification.request.content.userInfo; if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {[MTPushService handleRemoteNotification:userInfo]; } completionHandler(); // 係統要求執行這個方法} - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler { // Required, iOS 7 Support [MTPushService handleRemoteNotification:userInfo]; completionHandler(UIBackgroundFetchResultNewData); } - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo { // Required, For systems with less than or equal to iOS 6 [MTPushService handleRemoteNotification:userInfo]; }
          #pragma mark- MTPushRegisterDelegate

// iOS 12 Support
- (void)mtpNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {// 從通知介面直接進入應用程式}else{// 從通知設置介面進入應用程式}
}

// iOS 10 Support
- (void)mtpNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
  // Required
  NSDictionary * userInfo = notification.request.content.userInfo;
  if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {[MTPushService handleRemoteNotification:userInfo];
  }
  completionHandler(UNNotificationPresentationOptionAlert); // 需要執行這個方法,選擇是否提醒用戶,有 Badge、Sound、Alert 三種類型可以選擇設置
}

// iOS 10 Support
- (void)mtpNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
  // Required
  NSDictionary * userInfo = response.notification.request.content.userInfo;
  if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {[MTPushService handleRemoteNotification:userInfo];
  }
  completionHandler();	// 係統要求執行這個方法}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

  // Required, iOS 7 Support
  [MTPushService handleRemoteNotification:userInfo];
  completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

  // Required, For systems with less than or equal to iOS 6
  [MTPushService handleRemoteNotification:userInfo];
}

        
此代碼塊在浮窗中顯示

添加處理 MTPush 自訂訊息回調方法

如需使用 MTPush 的自訂訊息功能,請參考 iOS API 來實現自訂訊息的處理回調方法。

成功運行

真機調試該項目,如果控製台輸出以下日誌則代錶您已經集成成功。

2016-08-19 17:12:12.745823 219b28[1443:286814] | MTP | I - [MTCORETcpEventController] ----- login result ----- uid:123456 registrationID:171976fa8a8620a14a4 idc:0
          2016-08-19 17:12:12.745823 219b28[1443:286814] | MTP | I - [MTCORETcpEventController] 
----- login result -----
uid:123456 
registrationID:171976fa8a8620a14a4 
idc:0

        
此代碼塊在浮窗中顯示

高級功能

MTush SDK 相關事件監聽

建議開發者加上 API 裏面提供的以下類型的通知:

extern NSString _const kMTCNetworkIsConnectingNotification; // 正在連接中
extern NSString _ const kMTCNetworkDidSetupNotification; // 建立連接
extern NSString _ const kMTCNetworkDidCloseNotification; // 關閉連接
extern NSString _ const kMTCNetworkDidRegisterNotification; // 註冊成功
extern NSString _const kMTCNetworkFailedRegisterNotification; // 註冊失敗
extern NSString _ const kMTCNetworkDidLoginNotification; // 登入成功

溫馨提示: Registration id 需要添加註冊 kMTCNetworkDidLoginNotification 通知的方法裏獲取,也可以調用 [registrationIDCompletionHandler:] 方法,通過 completionHandler 獲取

extern NSString * const kMTCNetworkDidReceiveMessageNotification; // 收到自訂訊息(非 APNs)
其中,kMTCNetworkDidReceiveMessageNotification 傳遞的數據可以通過 NSNotification 中的 userInfo 方法獲取,包括標題、內容、extras 信息等,請參考文檔:iOS SDK API

通知送達統計

溫馨提示:
iOS 10 新增的 Notification Service Extension 功能,用 mutable-content 字段來控製。
若使用 Web 控製台,需勾選 “可選設置”中 mutable-content 選項;若使用 RESTFul API 需設置 mutable-content 字段為 true。

開發者可使用 Notification Service Extension SDK 上報每條 APNs 信息的送達狀態。

使用方法:

  • 創建一個 Service Extension 服務,詳情參考 iOS 10 Service Extension
  • -將mtpush-extension-ios-xxx.xcframework檔案引入到您的Service Extentsion工程中。
  • 添加 Framework:libz.tbd 和 libresolv.tbd。
  • 調用 [mtpushSetAppkey:] 方法設置您的 appkey,請註意這裏的 appkey 應該和您 EngageLab 應用程式的 appkey 相同。
  • 調用 [mtpushReceiveNotificationRequest:] 方法上報您的 apns 訊息,完成送達統計;在該方法的 block 回調中進行 apns 的顯示。

更具體的使用示例請參考版本壓縮包中附帶的 Demo 代碼。 參考文檔:iOS SDK API

技術支持

當出現問題時:

  • 請仔細閱讀文檔,查看是否有遺漏。
  • 你可以到 EngageLab 社區搜索類似問題。 為了更快速的解決問題,在尋求幫助時,請提供下列信息:
    • 你需要谘詢的産品是 MTPush,是否同時使用了 EngageLab 其他的産品 。
    • 你所調用的是什麼 API,所傳參數,完整的報錯信息,出現異常的時間點 。
    • 如果收不到訊息,提供應用程式的 Appkey,訊息的 Message ID,設備的 registration ID 信息 。
    • 如果是 SDK 問題請提供對應的 SDK 版本和完整的日誌記錄,日誌信息請使用 TXT 文件上載 。
    • 出現異常的設備是 iOS ,列出具體的機型和係統 。
在文档中心打开