APNs

Update time: 2023/02/09 16:04:15

Prerequisite

Create a request certificate

  • Click "Access to Keychain" in the OSX system to generate a request certificate.

  • Fill in a common email address in the page of certificate information, and save the address to the disk.

create a projectID

  • Log in to "iOS Dev Center" and access to "Certificates, Identifiers & Profiles".
  • Click "iOS Apps IDs" in the left navigation bar to enter the List of Identifiers - App IDs.
  • Click "+" symbol on the right side to create a project ID.

Enable push notifications

  • Click the created App, and select the "Edit" button.

  • Check "Push Notifications" feature, and click the "Configure Certificate" button to view the corresponding page. Development certificates have different types. The development certificate is used for development and debugging; the production certificate is used for release.

Configure a certificate

  • Upload the generated request certificate (CSR file), and click "Generate".

  • After the generation, download and upload the certificate. The certificate is automatically imported to the keychain. You can find the input certificate in " My certificate" under "Accessing the keychain ".

Export required p12 file for push notifications

  • Select the imported certificate and select the "Export" option under the right-click menu.
  • Please set a password when saving the p12 file, and fill in this password when uploading the certificate.

Upload the certificate

  • Log in to the CommsEase console, and select the corresponding app for accessing to Certificate Management->iOS Push Certificate.
  • Upload the exported p12 file as shown in the Figure. You can upload multiple p12 files to can distinguish the certificate name filled in when uploading.
  • Select the same environment where the certificate is generated. Two options: "development environment" [online environment] or "production environment" [test environment]

Client-side configuration

Configure a push certificate

Set the name of corresponding push certificate in NIMSDKOption.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    ...
    NSString *appKey    = @"your app key";
    NIMSDKOption *option  = [NIMSDKOption optionWithAppKey:appKey];
    option.apnsCername   = @"your APNs cer name";
    [[NIMSDK sharedSDK] registerWithOption:option];
    ...
}

Upload devicetoken

The client needs to upload devicetoken to the CommsEase server for APNs push notifications by using the following APIs.

@interface NIMSDK : NSObject
/**
* @param token - devicetoken of the current device 
* @param key - Customize the local-client push content, configure custom push text of server corresponding to key; input @""If configuration is cleared, nil cannot be changed.

- (NSString *)updateApnsToken:(NSData *)token 
             customContentKey:(nullable NSString *)key
}

Notes: For information on customContentKey, see user-defined push texts in Set the push text .

Sample codes:

- (void)registerPushService
{
    if (@available(iOS 11.0, *))
    {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!granted)
            {
                dispatch_async_main_safe(^{
                    [[UIApplication sharedApplication].keyWindow makeToast:@"Please enable push feature; otherwise, push notification cannot be received" duration:2.0 position:CSToastPositionCenter];
                })
            }
        }];
    }
    else
    {
        UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types
                                                                                 categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    }
    
    [[UIApplication sharedApplication] registerForRemoteNotifications];
    
  
    // Register the push permission for local push notifications.
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
}

...

- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // Upload a devicetoken to CommsEase server.
    [[NIMSDK sharedSDK] updateApnsToken:deviceToken];
}

Global mute

NIM SDK allows you to set Do Not Disturb with global APNs attributes. For more information, see NIMPushNotificationSetting.

  • Get the setting of Do Not Disturb push notifications.
NIMPushNotificationSetting *setting = [[[NIMSDK sharedSDK] apnsManager] currentSetting];
  • Update settings of push notifications:

Notes: Set start time and end time.

NIMPushNotificationSetting *setting = [NIMSDK sharedSDK].apnsManager.currentSetting;
// Enable the button of Do not disturb.
setting.noDisturbing = YES;
setting.noDisturbingStartH = s_hour;
setting.noDisturbingStartM = s_minute;
setting.noDisturbingEndH = e_hour;
setting.noDisturbingEndM = e_minute;
[[[NIMSDK sharedSDK] apnsManager] updateApnsSetting:setting  
                                         completion:^(NSError *error) {}];

Multi-client push notification policies

When a user is online on the desktop, the SDK supports setting whether to send push notifications to the mobile devices.

@protocol NIMApnsManager <NSObject>
/**
* Get configurations for multi-client push notifications
*/
- (nullable NIMPushNotificationMultiportConfig *)currentMultiportConfig;

/**
* Set configurations for multi-client push notifications
*/
- (void)updateApnsMultiportConfig:(NIMPushNotificationMultiportConfig *)config 
                       completion:(nullable NIMApnsHandler)completion;
@end

List of NIMPushNotificationMultiportConfig parameters:

Parameter Type Description
shouldPushNotificationWhenPCOnline BOOL When a user is online on the desktop, the SDK supports setting whether to send push notifications to the mobile devices. By default, set the parameter value as Yes. The desktop client includes PC, web, macOS.

Configure messages push

Set whether messages push are required

You can specify that a push notification is not required by using NIMMessage - NIMMessageSetting - apnsEnabled.

Sample codes:

NIMMessage *message = [[NIMMessage alloc] init];
message.text = @"Message example";
NIMMessageSetting *setting = [[NIMMessageSetting alloc] init];
setting.apnsEnabled = NO; //Set to "The push notification is not required."
message.setting = setting;

Set the push content

You can customize APNs push content in the notification bar by using NIMMessage - apnsContent. If you do not set apnsContentattribute, by default, the built-in CommsEase content will be set.

Attribute prototypes:

@interface NIMMessage : NSObject
/**
 * The maximum length of content for push notifications is 500.
 */
@property (nullable,nonatomic,copy)         NSString *apnsContent;
@end

Sample codes:

NIMAudioObject *audioObject = [[NIMAudioObject alloc] initWithSourcePath:filePath];
NIMMessage *message = [[NIMMessage alloc] init];
message.messageObject = audioObject;
message.apnsContent = @"Sent an audio file";  // The push text received by the other party.

At this time, the receiver will receive an APN in the form of "Nickname:"+"Push Copy". The nickname is the prefix of a push text.

  • Customize the default push text

If the developer configures "Hide text details" (see as follows for configuration methods), by default, you will receive a push text that "You've got a new message". At this time, the developer can customize the push text, such as systematic languages. Notes: You need to contact the business consultant to enable the feature. Log in to CommsEase Console-Select Application-Certificate Management-Custom Push Copy. You can set up to 100 user-defined texts. Each user-defined text is marked with one user-defined type.

You can not apply user-defined push text unless "Hide text details" are configured on the client Sample codes:

// Get the current configuration
NIMPushNotificationSetting *setting = [NIMSDK sharedSDK].apnsManager.currentSetting;
// Set to "Hide text details"
setting.type = NIMPushNotificationDisplayTypeNoDetail;
[[[NIMSDK sharedSDK] apnsManager] updateApnsSetting:setting completion:^(NSError *error) {}];
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // The uploaded devicetoken carries the custom types of push text.
    [[NIMSDK sharedSDK] updateApnsToken:deviceToken
                       customContentKey:@"customkey"];
}

Set the prefix of push text

You can set whether a prefix of push text is required by using NIMMessage - NIMMessageSetting - apnsWithPrefix. When CommsEase server sends APNs requests, the prefix is the user nickname. Sample codes:

NIMMessage *message = [[NIMMessage alloc] init];
message.text = @"Message example";
message.apnsContent = @"Example of push message";  //The push text is received by the other party 
NIMMessageSetting *setting = [[NIMMessageSetting alloc] init];
setting.apnsWithPrefix = NO;      //The prefix is not required.
message.setting = setting;

Unread count of badges

Assignment to unread count of badges

By default, the unread count of badges is increased by 1 for each push notification. For example, when App operates in the background and receives 5 push notifications, the unread count of badges increases by 5.

When sending a message, the sender can set whether the push notification is included in the unread count of badges by using NIMMessage - NIMMessageSetting - shouldBeCounted.

Sample codes:

NIMMessage *message = [[NIMMessage alloc] init];
message.text = @"Example messages without unread count";
NIMMessageSetting *setting = [[NIMMessageSetting alloc] init];
setting.shouldBeCounted = NO;  //It shall not be included in unread count of corner marks during push.
message.setting = setting;

The unread count in APN is configured by "badge" parameter in push payload CommsEase service does not support configuring "badge" parameter. The server will maintain the current unread count for each user. When receiving an unread message, the server will cumulate to unread count automatically, fill in pushed "badge" field, and push to the receiving client.

  • Manual assignment to the unread count of local badges

When the program switches to the background, the developer shall collect local unread count and set "badge" to ensure consistent unread count for program foreground and background. For example, an app receives a message in background now, and then an app badge will be 1. When an app returns to the foreground, the total unread count of a session is 1. At this time, an app receives another message and the total unread count of sessions will be 2. When app switches to the background again, the developer shall call iOS system method to assign 2 to badges.

Example:

- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSInteger count = [[[NIMSDK sharedSDK] conversationManager] allUnreadCount];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:count];
}
  • Customize CommsEase badge value

If App itself has other unread messages in addition to the unread count in CommsEase, the icon value in program will be the sum of CommsEase unread count and other unread counts. However, CommsEase server only maintains the unread count of messages by default, so that the unread count of new push notifications will not be included in the other unread count of App.

In this case, the client needs to submit the unread count that shall be managed by the server.

Prototype

@protocol NIMApnsManager <NSObject>
/**
 * Register the callback function for getting badge count
 *
 * @param handler - Get badge callback
 */
- (void)registerBadgeCountHandler:(NIMBadgeHandler)handler;
@end

If necessary, we recommend to register this callback function after initializing SDK([[NIMSDK sharedSDK] registerWithOption:option]). Besides, a global variable is returned in a callback, which can be updated subsequently in the process of executing the program as required. SDK will automatically read returned value and send it to the CommsEase server.

Upper limit of unread count of badges

The upper limit of the unread count of badges in iOS app can be configured at .CommsEase Console> Select Application> IM Professional/IM Free Version> Function Configuration> Configuration of unread count shown in iOS corner mark for notifications from CommsEase client.

Push sound setting

The sound configuration for push notifications supports user-defined mode, similar to pushed payload. The developer only needs to set NIMMessage - apnsPayload where a key-value pair with key sound shall be inserted. It is necessary to pay attention to the detailed format in which the push sound is made. See Apple official document for details..

Example

NIMMessage *message = [[NIMMessage alloc] init];
message.text = @"Message example";
message.apnsContent = @"Sent a message";
message.apnsPayload = @{@"sound":@"message.wav"};

Push title setting

CommsEase APNs now supports setting push titles by the following two methods:

  • The push title and text can be designated using setting two keys (title & body) in NIMMessage - apnsPayload - apsField - alert. This is the priority. Particularly, if alert field of apsField is configured, but title is void or not configured, then there is not push title and body is void or not configured with push text. If both are void or not configured, then there are no push tile and text. See the following example for details.
  • If a configuration is not made in apsField, but "pushTitle": "Title content" is configured with payload, then it shows like this.
  • If both are not configured, no title will be displayed.

The developer cannot configure aps field in the parameter "payload". IM provides push configuration field "payload - apsField", corresponding to "payload - aps" field of APNs. The field applies to iOS reception only, and Android cannot analyze this field. The following shows IM configured payload with apsField:

{
    // For display, the above sample code is formatted, but cannot be formatted when being sent.
    "key1": "value1", //Custom key value pair
    "apsField": {
        "mutable-content": 1,
        "sound": "abc.wav",
        "alert": {
            "title": "Push title",
            "body": "Push content"
        },
        "key2": "value2"
    }
}

Force to push team message

When sending a message, the user can force to push team message using configuring apnsMemberOption field in NIMMessage. That is, the receiver can still push the current message even when shielding the current session (e.g. mute).

@interface NIMMessageApnsMemberOption : NSObject
/**
* List of users requiring special push. If the field is nil, it means to push to all users in the current session.
*/
@property (nullable, nonatomic, copy) NSArray<NSString*> *userIds

/**
* The default value is "YES". If it is set to "YES", it means that current content can be pushed to related users even though users in a push list have blocked the current session (e.g. mute).
*/
@property (nonatomic, assign) BOOL forcePush

/**
* Push text, with length 500
*/
@property (nullable, nonatomic, copy) NSString *apnsContent
@end

Click notification bar to skip

If the user wants to access the designated chat API after receiving APNs and clicking notification bar, the user can refer to the following solution:

When creating a message object, the sender inserts information, such as the account, team ID, session type) that can indicate session token in NIMMessage - apnsPayload to get resolution from APNs - payload at receiving client. For example,

{
    // For display, the above sample code is formatted, but cannot be formatted when being sent.
    "sessionid": "zhangsan", //It means an account of the message sender or team ID for the message.
    "sessiontype": "P2P",  //It means one-to-one chat or team chat of session corresponding to the message.
    "apsField": {
        "mutable-content": 1,
        "sound": "abc.wav",
        "alert": {
            "title": "Push title",
            "body": "Push content"
        },
        "key2": "value2"
    }
}

When receiving APNs at receiving client, the user can get sessionid and sessiontype using resolving APNs - payload, and skip to the corresponding API.

Cover content of notification bar

iOS 10 and above support to cover push notifications, i.e. the last content covers the previous content. A typical scenario is to revoke messages:

A sends a message to B to generate APNs with text content "Hello". Then A revokes this message and "Hello" shown in the notification bar becomes the default "revoked a message".

A recommended realization method:

  • When sending a message, the user needs to insert key value with key being apns-collapse-id in NIMMessage - apnsPayload. we recommend filling in character strings such as "uuid" in value for unique identification.
  • When revoking this message, the user needs to configure text in transfer parameter apnsContent and insert the same apns-collapse-id with a revoked message in apnsPayload.

Notes: iOS-SDK is taken as an example here. It is the same for revoking messages from other clients.

Example:

NSDictionary *payload = @{@"apns-collapse-id": Id};
[[NIMSDK sharedSDK].chatManager revokeMessage:message
                                  apnsContent:@"Revoke a message"
                                  apnsPayload:payload
                              shouldBeCounted:![[NTESBundleSetting sharedConfig] isIgnoreRevokeMessageCount]
                                   completion:^(NSError * _Nullable error){}];
Was this page helpful?
Yes
No
  • Prerequisite
  • Create a request certificate
  • create a projectID
  • Enable push notifications
  • Configure a certificate
  • Export required p12 file for push notifications
  • Upload the certificate
  • Client-side configuration
  • Configure a push certificate
  • Upload devicetoken
  • Global mute
  • Multi-client push notification policies
  • Configure messages push
  • Set whether messages push are required
  • Set the push content
  • Set the prefix of push text
  • Unread count of badges
  • Assignment to unread count of badges
  • Upper limit of unread count of badges
  • Push sound setting
  • Push title setting
  • Force to push team message
  • Click notification bar to skip
  • Cover content of notification bar