iOS SDK Integration Guide

Last updated:2022-12-14

Applicable version

This article matches the MTPush iOS SDK version: v3.0.0 and later.

Resource file

Package Name engagelab-ios-{version number}

Starting from version 4.3.3, the .a package will no longer be provided. Only .xcframework packages will be offered.

  • lib folder: Contains mtpush-ios-x.x.x.xcframework, mtpush-extension-ios-x.x.x.xcframework. (Please note: APNs are not supported on simulators).
  • README file: SDK related instructions
  • demo folder: Examples

Obtaining Application Information

After an application is created on the console, an AppKey is automatically generated to identify the application.

The configuration of Project

Import the SDK

Cocoapods import

pod 'MTPush' Note: If you cannot import the latest version, run the pod repo update master command to update the local pod library and then re-pod 'MTPush'.
              pod 'MTPush'

    Note: If you cannot import the latest version, run the pod repo update master command to update the local pod library and then re-pod 'MTPush'.

        
This code block in the floating window
  • If you need to install the specified version, use the following method (using MTPush 3.5.0 as an example) :
pod 'MTPush', '3.5.0'
              pod 'MTPush', '3.5.0'

        
This code block in the floating window

Manual import

  • Unzip the SDK package, in Xcode, select "Add files to 'Your project name'...", and add mtpush-ios-x.x.x.xcframework to your project directory.
  • Add 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

If your project requires support for iOS operating systems less than 7.0, please go to Build Settings and turn off bitCode option. Otherwise, it will not compile properly.

  • Set User Header Search Paths and Library Search Paths under Search Paths. For example, the SDK folder (default is lib) is in the same level as the project file. Set this parameter to $(SRCROOT)/{Name of the folder where the static library resides}.

Capabilities

If developing with Xcode 8 and above, enable the Capabilities->Push Notifications option in the Application Target, as shown here: 1.png
If you are developing in an Xcode 10 or above environment, enable the Capabilities-> Access WIFI Infomation option on your Application Target.
image.png

Adding a header file

Add the following code to the location of the AppDelegate.m reference header file.

// import MTPush Function required header file #import "MTPushService.h" // iOS10 Register the required header file for APNs #ifdef NSFoundationVersionNumber_iOS_9_x_Max #import <UserNotifications/UserNotifications.h> #endif // Header files to introduce if you need to use idfa functionality (optional) #import <AdSupport/AdSupport.h>
          // import MTPush Function required header file
#import "MTPushService.h"
// iOS10 Register the required header file for APNs
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
// Header files to introduce if you need to use idfa functionality (optional)
#import <AdSupport/AdSupport.h>

        
This code block in the floating window

Add the Delegate

Add a Delegate to the AppDelegate. Refer to the following code:

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

@end

        
This code block in the floating window

Add the initialization code

Add the initialization APNs code

Please add the following code to -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

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

        
This code block in the floating window

Add the initialization MTPush code

Please add the following code to -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

// Optional // Get the IDFA // To use the IDFA function, add this code and fill in the advertisingIdentifier parameter for the initialization method NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString]; // Required // init Push [MTPushService setupWithOption:launchOptions appKey:appKey channel:channel apsForProduction:isProduction advertisingIdentifier:advertisingId];
          // Optional
// Get the IDFA
// To use the IDFA function, add this code and fill in the advertisingIdentifier parameter for the initialization method
NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];

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

        
This code block in the floating window
Part Parameter Description
  • appKey
    • Ensure that the appkey configured in the application is the same as that generated after the application is created on the Console.
  • channel
    • Specify the download channel of the application package. For the convenience of statistics by channel, you can define the specific value by yourself, such as App Store.
  • apsForProduction
    • This parameter identifies the APNs certificate environment used by the current application.
    • 0 (default value) indicates that a development certificate is used, and 1 indicates that a production certificate is used to publish applications.
    • Note: The value of this field must be the same as the certificate environment configured in Code Signing for Build Settings.

APNs is successfully registered and DeviceToken is reported.

tips: You can log in to EngageLab without calling this method. However, APNs notifications are not available, only can use the custom messages.

Implement the callback method in AppDelegate.m and add the code in the callback method:

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

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

        
This code block in the floating window

Implement APNs registration failure interface (Optional)

- (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];
}

        
This code block in the floating window

Add a callback method for handling APNs notifications

Implement the callback method in AppDelegate.m and add the code in the callback method:

#pragma mark- MTPushRegisterDelegate // iOS 12 Support - (void)mtpNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {// Directly enter the application from the notification interface.}else{// Enter the application from the notification settings interface.} } // 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); // To execute this method, choose whether to Alert the user or not. There are three types of Badge, Sound, and alert that can be set } // 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(); // The system requires this method to be executed} - (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]]) {// Directly enter the application from the notification interface.}else{// Enter the application from the notification settings interface.}
}

// 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); // To execute this method, choose whether to Alert the user or not. There are three types of Badge, Sound, and alert that can be set
}

// 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();	// The system requires this method to be executed}

- (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];
}

        
This code block in the floating window

Added a callback method to handle MTPush custom messages

To use MTPush's custom message functionality, see the 【iOS API Guide】 to implement custom message processing callbacks.

Run successfully

Debug the project. If the console outputs the following log, you have successfully integrated.

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

        
This code block in the floating window

If you encounter any problems during debugging, please refer to 【iOS SDK Debugging Guide】.

Advanced features

It is recommended that developers include the following types of notifications provided in the API:

extern NSString *const kMTCNetworkIsConnectingNotification; // Establishing now
extern NSString * const kMTCNetworkDidSetupNotification; // Establish a connection
extern NSString * const kMTCNetworkDidCloseNotification; // Close the connection
extern NSString * const kMTCNetworkDidRegisterNotification; // Registered successfully
extern NSString *const kMTCNetworkFailedRegisterNotification; // Registration failed
extern NSString * const kMTCNetworkDidLoginNotification; // Login successful

Warm tips: Add and register kMTCNetworkDidLoginNotification notice method and get the Registration id in this method,also can call registrationIDCompletionHandler: method, Get it through the completionHandler

extern NSString * const kMTCNetworkDidReceiveMessageNotification; // Received custom message (non-APNS)
KMTCNetworkDidReceiveMessageNotification transfer of data can be obtained by means of the userInfo in NSNotification, including title, content, and extras information, etc., please refer to the document: iOS SDK API

Service of Notice Statistics

Warm tips: The Notification Service Extension is a new feature in iOS 10, which is controlled by the mutable-content field. If you are using the Web console to push, check the mutable-content option in Optional Settings. If you use a RESTFul API to push, set the mutable-content field to true.

Developers can use the Notification Service Extension SDK to report the delivery status of each APNs message.

How to use:

  • Create a Service Extension Service. For details, see iOS 10 Service Extension.
  • Import the mtpush-extension-ios-xxx.xcframework file into your Service Extension project.
  • Add Framework: libz.tbd and libresolv.tbd.
  • Call [mtpushSetAppkey:] to set your appkey. Please note that this appkey should be the same as the appkey in your EngageLab application.
  • Call [mtpushReceiveNotificationRequest:] method to report your apns, statistics have been duly served; Display the apns in the method's block callback.

For more specific usage examples, refer to the Demo code included in the version zip package. Reference document:iOS SDK API

Technical support

When problems occur during integration

  • Please read the document carefully to see if there are any omissions.
  • You can go to EngageLab to search for a similar question. In order to solve the problem more quickly, please provide the following information when asking for help:
    • The product you need to consult is MTPush, whether to use other EngageLab products.
    • What API you are calling, the parameters you are passing, the complete error message, and the point in time when the exception occurred.
    • If no Message is received, provide the Appkey of the application, Message ID of the message, and registration ID of the device.
    • If the fault is caused by SDK, please provide the corresponding SDK version and complete log records. Upload log information using the TXT file.
    • The abnormal device is iOS. Please provide the specific model and system.
在文档中心打开