Applicable version
The version of MTPush iOS SDK matched in this paper is v3.0.0 or later.
Get the APNs (notification) push content
Function description
The iOS device receives a push notification (APNs). When the user clicks the push notification to open the application, the application processes according to different states. Needs add the following two methods in the AppDelegate to obtain the apn content.
- If the state of the App is not running, this function will be called, if launchOptions include UIApplicationLaunchOptionsRemoteNotificationKey means that the app is launched by user clicking the apns notification. If there is no this key value, it means that the App is not started by clicking apn, but may be started by directly clicking icon or other.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
// apn Content acquisition:
NSDictionary *remoteNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey]
- On iOS 6 and below, this function is called when the App is in the foreground or when a notification message is clicked in the notification bar. You can also determine whether the application is running in the foreground by checking whether the AppDelegate's applicationState is UIApplicationStateActive. Such cases are handled in this function:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo;
- Based on iOS 7 or later, if the Remote Notification feature of iOS 7 is used, the processing function needs to use:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler;
- Based on the iOS 10 and above version of the system, the original [application: didReceiveRemoteNotification:] will be discarded by the system,
By the new UserNotifications Framework of [UNUserNotificationCenterDelegate willPresentNotification: withCompletionHandler:] Or [UNUserNotificationCenterDelegate didReceiveNotificationResponse: withCompletionHandler:] to replace. In the current version or later, you can implement the MTPushRegisterDelegate protocol method encapsulated by the SDK and adapt to the newly added delegate protocol method in iOS10. Namely, the following two methods:
- (void)mtpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler;
// NSDictionary * userInfo = notification.request.content.userInfo;
// The APNs content is userInfo
- (void)mtpNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler;
// NSDictionary * userInfo = response.notification.request.content.userInfo;
// The APNs content is userInfo
The sample code
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// Obtain the APNs standard information content
NSDictionary *aps = [userInfo valueForKey:@"aps"];
NSString *content = [aps valueForKey:@"alert"]; //Push the displayed content
NSInteger badge = [[aps valueForKey:@"badge"] integerValue]; //The badge number
NSString *sound = [aps valueForKey:@"sound"]; //The sound played
// Gets the Extras field content
NSString *customizeField1 = [userInfo valueForKey:@"customizeExtras"]; //Extras field on the server, key is defined by itself
NSLog(@"content =[%@], badge=[%d], sound=[%@], customize field =[%@]",content,badge,sound,customizeField1);
// iOS 10 以下 Required
[MTPushService handleRemoteNotification:userInfo];
}
//iOS 7 Remote Notification
- (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
NSLog(@"this is iOS7 Remote Notification");
// iOS 10 以下 Required
[MTPushService handleRemoteNotification:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
}
#pragma mark- MTPushRegisterDelegate // MTPushRegisterDelegate was added in 2.1.9. The following two methods need to be implemented
// 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];
}
else {
// Local notifications
}
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];
}
else {
// Local notifications
}
completionHandler(); // The system requires this method to be executed
}
- Based on iOS12 or above, UserNotifications Framework of new callback methods [userNotificationCenter: openSettingsForNotification:], in 3.1.1 and above version MTPushRegisterDelegate also added the corresponding callback methods. This method is called back when the application is accessed from the external notification screen or notification Settings screen.
// iOS 12 Support
- (void)mtpNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification{
if (notification) {
//Enter the application directly from the notification screen
}else{
//Enter the application directly from the notification screen
}
}
参考文档:Handling Local and Remote Notifications
Get the content of the custom message push
Function description
- Custom messages are pushed only when the front end is running.
- Get the custom message content and title and additional fields from the MTPush server.
Implementation method
Getting push content from iOS requires registering notifications in the delegate class and implementing callback methods.
In the method - (BOOL) application: (UIApplication) application didFinishLaunchingWithOptions: (NSDictionary) launchOptions add the following code:
NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
[defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kMTCNetworkDidReceiveMessageNotification object:nil];
Implement the callback method networkDidReceiveMessage
- (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"]; //The Extras extra field passed by the server, the key is self-defined
}
Parameters description
- content:Get the content of the push
- messageID:Get the push messageID (key: @"_j_msgid")
- extras:Get user-defined parameters
- customizeField1:Obtain a customized value based on the customized key
For more information, refer to the demo in the SDK download package.
Get RegistrationID
RegistrationID definition
The first time an application integrated with the MTPush SDK successfully registers with the MTPush server, the MTPush server returns to the client a unique identifier for the device - RegistrationID. The MTPush SDK sends the RegistrationID as a broadcast to the application.
An application can save this RegistrationID on its application server and then push messages or notifications to the device based on the RegistrationID.
Get registrationID (with block)
The interface definition
+ (void)registrationIDCompletionHandler:(void(^)(int resCode,NSString *registrationID))completionHandler;
Parameters description
- (void(^)(int resCode,NSString *registrationID))completionHandler
- completionHandler: Used to process the return result of the Settings
- resCode: Return the result status code
- registrationID: Returns the registrationID
[MTPushService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
NSLog(@"resCode : %d,registrationID: %@",resCode,registrationID);
}];
Warm tips: It is recommended that you use this interface to get the registrationID. Calling this interface in the emulator resCode returns 1011 and the registrationID returns nil.
Get registrationID
Call this API to get the RegistrationID for the application. The corresponding value is returned only if the application successfully registers with MTPush's server, otherwise an empty string is returned.
The interface definition
+(NSString *)registrationID
Warm tips: On iOS 9, applications are uninstalled and reinstalled. The devicetoken returned by APNs will change. The developer needs to obtain the latest Registration id of the device. , please call "RegistrationID" this interface in kMTCNetworkDidLoginNotification implementation method to obtain RegistrationID.
Additional instructions
Push messages and notifications through the RegistrationID
Notifications and messages can be pushed using the RegistrationID. The audience parameter can be pushed based on the RegistrationID.
Set the Badge
Function description
badge is a number used by iOS to mark the status of an app. It appears in the upper right corner of the app icon. MTPush encapsulates the badge function, allowing applications to upload badge values to the MTPush server. The MTPush background helps to manage the corresponding push badge values for each user, simplifying the operation of setting push badge.
In practice, developers can directly add or subtract badge values without having to maintain the relationship between users and badge values. To push messages, simply set corner sign +1, EngageLab will automatically +1 on each user's badge value stored in the server and then down to the user.
Set the badge
Sets the badge value stored in the MTPush server
The interface definition
+ (BOOL)setBadge:(int)value
Parameters description
- value The value ranges from 0 to 99999.
Local must still be called UIApplication: setApplicationIconBadgeNumber function Settings icon is displayed on the badge
- The return value
- Return TRUE within the range of value; otherwise, return FALSE
Empty the badge
Clear the badge value stored in the MTPush server, i.e. [setBadge:0]
The interface definition
+ (void)resetBadge
Local notifications
Function description
The iOS device receives a local notification. When the user clicks the notification to open the app, the app handles the situation according to different states. Code needs to be added to the following two methods in the AppDelegate to obtain the local notification content:
- If the state of the App is not running, this function is called, if launchOptions include UIApplicationLaunchOptionsLocalNotificationKey indicates user clicks on a local notification lead to App is up and running; If there is no corresponding key value, it means that the App is not started by clicking the local notification, which may be started by directly clicking the icon or other.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
// Obtain the local notification content:NSDictionary *localNotification = [launchOptions objectForKey: UIApplicationLaunchOptionsLocalNotificationKey]
- This function is called if the App state is foreground or background running, and you can determine if the AppDelegate's applicationState is UIApplicationStateActive. Such cases are handled in this function:
// NS_DEPRECATED_IOS(4_0, 10_0, "Use UserNotifications Framework's -[UNUserNotificationCenterDelegate willPresentNotification:withCompletionHandler:] or -[UNUserNotificationCenterDelegate didReceiveNotificationResponse:withCompletionHandler:]")
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification;
//The local notification is notification
- The above method will be deprecated in iOS 10 and above. By the new UserNotifications Framework of - [UNUserNotificationCenterDelegate willPresentNotification: withCompletionHandler:] or - [UNUserNotificationCenterDelegate didReceiveNotificationResponse: withCompletionHandler:] to replace. To this end, SDK encapsulates the MTPushRegisterDelegate protocol, which can be adapted to the newly added delegate method in iOS 10 only by implementing the corresponding protocol method, which is consistent with the above remote push callback method, namely, the following method:
- (void)mtpNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^) (NSInteger))completionHandler;
// if (![notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
// The local notification is notification
// }
- (void)mtpNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler: (void (^)())completionHandler;
// if (![response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
// The local notification is notification
// }
Register/update local notifications
Function description
The API is used to register or update push (iOS 10 supported and compatible with iOS 10 and below).
The interface definition
+ (void)addNotification:(MTPushNotificationRequest *)request;
Parameters description
- Request [MTPushNotificationRequest] entity type, can be introduced to push properties.
Get description
Put the request.requestIdentifier in the request as the parmameter to update the push that already have, otherwise register to a new push.
Code sample
- (void)testAddNotification {
MTPushNotificationContent *content = [[MTPushNotificationContent alloc] init];
content.title = @"Test Notifications";
content.subtitle = @"2016";
content.body = @"This is a test code";
content.badge = @1;
content.categoryIdentifier = @"Custom Category Name";
// Alert iOS 10 or later after 5s
MTPushNotificationTrigger *trigger1 = [[MTPushNotificationTrigger alloc] init];
trigger1.timeInterval = 5;
//Repeat iOS 10 + support once per hour
MTPushNotificationTrigger *trigger2 = [[MTPushNotificationTrigger alloc] init];
trigger2.timeInterval = 3600;
trigger2.repeat = YES;
//Alert every Monday at 8:00 AM, iOS 10 and above support
NSDateComponents *components = [[NSDateComponents alloc] init];
components.weekday = 2;
components.hour = 8;
MTPushNotificationTrigger *trigger3 = [[MTPushNotificationTrigger alloc] init];
trigger3.dateComponents = components;
trigger3.repeat = YES;
//#import <CoreLocation/CoreLocation.h>
//Alert when you arrive at a location, iOS 8 and above support
CLLocationCoordinate2D cen = CLLocationCoordinate2DMake(37.335400, -122.009201);
CLCircularRegion *region = [[CLCircularRegion alloc] initWithCenter:cen
radius:2000.0
identifier:@"engagelab"];
MTPushNotificationTrigger *trigger4 = [[MTPushNotificationTrigger alloc] init];
trigger4.region = region;
//Alert after 5s, support below iOS 10
MTPushNotificationTrigger *trigger5 = [[MTPushNotificationTrigger alloc] init];
trigger5.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
MTPushNotificationRequest *request = [[MTPushNotificationRequest alloc] init];
request.requestIdentifier = @"sampleRequest";
request.content = content;
request.trigger = trigger1;//trigger2;//trigger3;//trigger4;//trigger5;
request.completionHandler = ^(id result) {
NSLog(@"Results back:%@", result);
};
[MTPushService addNotification:request];
}
Removing Local Notifications
Function description
The API is used to remove notifications that are ready to be pushed or have been displayed in the notification center. (iOS 10 is supported and compatible with versions later than iOS 10.)
The interface definition
+ (void)removeNotification:(MTPushNotificationIdentifier *)identifier;
Parameters description
- Identifier MTPushNotificationIdentifier entity type.
Get description
- With identifier set to nil above iOS 10, all display push and push requests in the notification center are removed. You can also remove corresponding push or to-be-pushed requests from the notification center by setting identifiers.delivered and identifiers.identifiers. identifiers if set to nil or an empty array remove all push or to-push requests displayed in the notification center under the corresponding flag.
- IOS below 10 identifier is set to nil, then remove all push, identifier. Delivered attribute is invalid, the other can be achieved by identifier. NotificationObj into specific push objects to remove to push this push.
Code sample
- (void)testRemoveNotification {
MTPushNotificationIdentifier *identifier = [[MTPushNotificationIdentifier alloc] init];
identifier.identifiers = @[@"sampleRequest"];
identifier.delivered = YES; //If it is equal to YES, it will be removed in the notification center display. If it is equal to NO, it will be removed in the notification center to be pushed. Invalid for iOS 10 or below
[MTPushService removeNotification:identifier];
}
- (void)testRemoveAllNotification {
[MTPushService removeNotification:nil]; // Removed all pushes from iOS 10 and below; iOS 10 or later removes all push and to be pushed requests displayed in the notification center
// //Support for iOS 10 and above
// MTPushNotificationIdentifier *identifier = [[MTPushNotificationIdentifier alloc] init];
// identifier.identifiers = nil;
// identifier.delivered = YES; //If it is equal to YES, it removes all that is displayed in the notification center, and if it is equal to NO, it removes all that is waiting to be pushed
// [MTPushService removeNotification:identifier];
}
Find Local Notifications
Function description
The API is used to find the push (iOS 10 supported and compatible with iOS 10 or later).
The interface definition
+ (void)findNotification:(MTPushNotificationIdentifier *)identifier;
Parameters description
- identifier [MTPushNotificationIdentifier]Entity type
Get description
- For iOS 10 and above, you can set identifiers.delivered and identifiers to find the corresponding push or to be pushed requests displayed in the notification center. if set identifiers to nil or an empty array return all requests to display push or to be pushed in the notification center under the corresponding flag; The following identifiers attribute in iOS 10 is invalid. delivered.identifiers return all unfired pushes if set to nil or an empty array.
- You need to set identifier.FindCompletionHandler callback to get search results, through (NSArray * results) returns an array of objects accordingly.
Code sample
- (void)testFindNotification {
MTPushNotificationIdentifier *identifier = [[MTPushNotificationIdentifier alloc] init];
identifier.identifiers = @[@"sampleRequest"];
identifier.delivered = YES; //If it is equal to YES, it will search in the notification center display; if it is equal to NO, it will search in the notification center to be pushed. Invalid under iOS10
identifier.findCompletionHandler = ^(NSArray *results) {
NSLog(@"The return result is:%@", results); // For iOS10 and above, an array of UILocalNotification objects is returned. For iOS10 and above, an array of UNNotification or UNNotificationRequest objects is returned based on the delivered value
};
[MTPushService findNotification:identifier];
}
- (void)testFindAllNotification {
MTPushNotificationIdentifier *identifier = [[MTPushNotificationIdentifier alloc] init];
identifier.identifiers = nil;
identifier.delivered = YES; //iOS 10 or above is valid. If YES is used to find all the messages displayed in the notification center, and if NO is used to find all the messages waiting to be pushed. Invalid for iOS 10 or below
identifier.findCompletionHandler = ^(NSArray *results) {
NSLog(@"The return result is:%@", results); // For iOS 10 and above, an array of UILocalNotification objects is returned. For iOS 10 and above, an array of UNNotification or UNNotificationRequest objects is returned based on the delivered value
};
[MTPushService findNotification:identifier];
}
Log Level Setting
Enabling Debug Mode
Function description
The API is used to enable the Debug mode to display more log information.
The interface definition
+ (void)setDebugMode;
Get description
When you need more debugging information, call the API to enable the Debug mode.
Code sample
[MTPushService setDebugMode];
Disable Log Information
Function description
The API is used to turn off logging messages (except for the necessary error messages).
The interface definition
+ (void)setLogOFF;
Get description
Call this API when you do not need any debugging information (it is recommended to call this API when publishing to mask log information and save performance).
Code sample
[MTPushService setLogOFF];
Setting a Mobile Phone Number
Function description
It is used to supplement sms messages. After you set the mobile phone number, you can realize the notification mode of "the SMS cannot be pushed", and improve the push fulfillment rate. After set the mobile phone number, it will push the sms message to device as supplement when normal message can not arrive,and it can improve the push delivery success rate.
The interface definition
+ (void)setMobileNumber:(NSString *)mobileNumber completion:(void (^)(NSError *error))completion
Parameters description
- mobileNumber Mobile phone number. The value can only start with a (+) or a digit. The value can only contain hyphens (-) and digits and cannot exceed 20 characters. If nil or empty string is passed, the number is unbound.
- completion responds to the callback. In the case of success, error is null. In the case of failure, error contains error codes and error information. For details about the error codes, see the definition of error codes.
Get description
This interface can be invoked a maximum of 3 times within 10s. You are advised to invoke this interface after the login succeeds. The result information is returned asynchronously through completion, or you can set completion to nil and not process the result information.
Code sample
[MTPushService setMobileNumber:@"xxx" completion:^(NSError *error) {
if (error) {
NSLog(@"error:%@", error);
}
else {
// success
}
}];
Reporting Language Information
Function description
API is used to report user language information
The interface definition
+ (void)setUserLanguage:(NSString *)language completionHandler:(void(^)(int resCode, NSError *error))handler;
Parameters description
- language:Language information
- handler:Report to the callback
Get description
It is recommended that you call this interface after successful login.
Code sample
[MTPushService setUserLanguage:@"zh_Hans" completionHandler:^(int resCode, NSError *error) {
NSLog(@"language report: %d, %@", resCode, error);
}];
Notification Service Extension
Supported Versions
Notification Service Extension SDK v3.0.0 or later versions.
Function description
Notification Service Extension SDK will be used for reporting the push arrived info.
Example Set the appkey interface
To set the appkey interface, it must be called in advance
The interface definition
+ (void)mtpushSetAppkey:(NSString *)appkey
Parameters description
- The appkey should be the same as the MTPush SDK appkey in the main app
Message display statistics
The message is sent to the statistics interface, which is called to report MTPush data in the APNs message body.
The interface definition
+ (void)mtpushReceiveNotificationRequest:(UNNotificationRequest *)request with:(void (^)(void))completion
Parameters description
- request UNNotificationRequest
- Perform operations, such as displaying APNs, on the completion message sent report callback.
Close the log
It is enabled by default. You are advised to disable it when publishing to reduce unnecessary I/O.
The interface definition
+ (void)setLogOff