APNs

Update time: 2024/03/14 17:08:34

Prerequisites

Create a certificate signing request

  • Launch Keychain Access located in /Applications/Utilities in Mac OS X.

  • In the Certificate Assistant dialog, enter an email address in the User Email Address field and choose "Saved to disk".

Create App ID

  • Once you have signed in to the iOS Dev Center, click on Certificates, IDs & Profiles.
  • Select Identifiers > App IDs in the left sidebar.
  • Click on the plus button in the top right corner to create an App ID.

Enable APNS

  • Choose an App ID you want to create a push certificate for and click Edit.

  • Select Push Notifications and click Create Certificate to configure the certificate. Note that the Development SSL Certificate is used for testing and Production SSL Certificate is used for production.

Configure the certificate

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

  • After downloading and opening the certificate, the certificate will be automatically imported into the keychain.

    You can find the imported certificate in "My Certificates" in "Keychain Access".

Export the p12 file

  • Right-click on the certificate and select Export "Apple Production iOS Push Services ..." option.

  • When exporting the certificate, you can provide a password for the p12 file. The password is required for uploading the certificate.


Upload the certificate

  • Go to the CommsEase console, select your application -> Certificate Management->iOS Push Certificate.

  • Upload the p12 file you just exported. Multiple p12 files can be uploaded. The files must have unique names.

  • The certificates must be used for production environment or development environment as generated.

Client configuration

Set the push certificate

On Android and iOS apps, the length of the push certificate name cannot exceed 32 characters, otherwise error 500 will be reported when logging in.

Set the push certificate name in NIMSDKOption.

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

Upload devicetoken

The client must upload the devicetoken to the CommsEase server for the APNs service, and the following interface is used:

objc@interface NIMSDK : NSObject
/**
* @param token  The devicetoken of the current device 
* @param key Custom push content. set the key to send custom push content to the business server; Pass in @"" to clear the configuration, nil will not change the setting.

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

Note: For the information about customContentKey, see [Set the notification body in payload](/en/docs/TM5MzM5Njk/DMxMjU0MDY?#Set the body of a notification).

Sample code:

objc- (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:@"Enable the push service, otherwise, push notifications 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 displaying push notifications.
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
}

...

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

Do-Not-Disturb

NIM SDK provides global settings of APNs, used to set the duration for the do-not-disturb status. For more information, see NIMPushNotificationSetting.

  • Get the configuration of Do-Not-Disturb for push services:
objcNIMPushNotificationSetting *setting = [[[NIMSDK sharedSDK] apnsManager] currentSetting];
  • Change the settings of push services:

NOTE: make sure you set the start and end time at the same time.

objcNIMPushNotificationSetting *setting = [NIMSDK sharedSDK].apnsManager.currentSetting;
// Enable 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-device alerts**

The SDK allows you to specify whether push notifications are sent to mobile clients when desktop clients are online.

objc@protocol  NIMApnsManager <NSObject>
/**
*  Get the configuration for synchronizing push notifications across devices.
*/
- (nullable NIMPushNotificationMultiportConfig *)currentMultiportConfig;

/**
* Set the configuration for synchronizing push notifications across devices.
*/
- (void)updateApnsMultiportConfig:(NIMPushNotificationMultiportConfig *)config 
                       completion:(nullable NIMApnsHandler)completion;
@end

NIMPushNotificationMultiportConfig represenation:

Parameter Type Description
shouldPushNotificationWhenPCOnline BOOL Whether push notifications are sent to mobile clients when the desktop client is online. The default value is YES, indicating that push notifications are synchronized across devices. The desktop client includes PC, web, and macOS.

Configure the push service

Whether the push service is enabled for messages

To specify whether the push service is required for a specified message, set the NIMMessage - NIMMessageSetting - apnsEnabled parameter.

Sample code:

objcNIMMessage *message = [[NIMMessage alloc] init];
message.text = @"Sample message";
NIMMessageSetting *setting = [[NIMMessageSetting alloc] init];
setting.apnsEnabled = NO; //Set the value to NO, the message will not be sent using the push service.
message.setting = setting;

Set the body of a push notification

If you want to customize the body of a push notification (the text displayed on the notification bar), you can set the body using NIMMessage - apnsContent. If you do not specify the body, the built-in content will be used.

Prototype

objc@interface NIMMessage : NSObject
/**
 *  Notification content up to 500 characters.
 */
@property (nullable,nonatomic,copy)                  NSString *apnsContent;
@end

Sample code:

objcNIMAudioObject *audioObject = [[NIMAudioObject alloc] initWithSourcePath:filePath];
NIMMessage *message = [[NIMMessage alloc] init];
message.messageObject = audioObject;
message.apnsContent = @" sent an audio message";    //The text displayed when a recipient receives a push notification. 

The recipient will receive a push notification delivered by the APNs service in "nickname:" "push copy" format. The nickname is the prefix of the push notification.

  • Use a custom content

If the details of a push notification are not displayed (see the setting below), the default text: "You have received a new message". You can add a custom body for a push notification (for example, use a custom body based on the system language). Note that you must contact the sales to activate the service.

Log in to CommsEase console - Application - Certificate Management - Custom body. You can configure up to 100 custom bodies, and each custom text is identified by a custom type.

If "Do not display the details" is configured, the custom body will be displayed.

Sample code:

objc// Get the configuration of Do-Not-Disturb.
NIMPushNotificationSetting *setting = [NIMSDK sharedSDK].apnsManager.currentSetting;
*  Hide the details of a push notification
setting.type = NIMPushNotificationDisplayTypeNoDetail;
[[[NIMSDK sharedSDK] apnsManager] updateApnsSetting:setting completion:^(NSError *error) {}];
objc- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    // Upload devicetoken with the custom body of a push notification.
    [[NIMSDK sharedSDK] updateApnsToken:deviceToken
                       customContentKey:@"customkey"];
}

Set the head of a push notification

To specify whether the prefix of a specified push notification is required, set the NIMMessage - NIMMessageSetting - apnsEnabled parameter. The CommsEase server use the user's nickname as prefix for a push notification for APNs..

Sample code:

objcNIMMessage *message = [[NIMMessage alloc] init];
message.text = @"Sample message";
message.apnsContent = @"Sample notification";    //The push notification received. 
NIMMessageSetting *setting = [[NIMMessageSetting alloc] init];
setting.apnsWithPrefix = NO;           //No prefix is required.
message.setting = setting;

Unread count badge

Assign the unread count

By default, the unread count will increment by 1 for each push notification. For example, when the app is running in the background and receives 5 push notifications, the unread count of the badge will increment by 5.

When sending a message, the sender can use NIMMessage - NIMMessageSetting - shouldBeCounted to set whether push notifications are counted as unread.

Sample code:

objcNIMMessage *message = [[NIMMessage alloc] init];
message.text = @"No sample message for unread count";
NIMMessageSetting *setting = [[NIMMessageSetting alloc] init];
setting.shouldBeCounted = NO;    //Push notifications do not increment the unread count at the badge.
message.setting = setting;

The unread count of APNS is set by setting [payload](https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/PayloadKeyReference.html#//apple_ref/doc/uid/TP40008194 The badge parameter in -CH17-SW1). On the CommsEase server, the badge is not directly set The server will maintain a current unread count for each user. When the server receives an unread message, it will automatically increment the unread count and assign the unread count in the badge field when delivering the unread message to clients.

  • Manually assign the local unread count

You must manage the local unread count every time the app is switched to the background, and set a badge to ensure that the unread counts of the app are consistent in the foreground and background.. For example, if an app receives a message in the background, the badge of the app increments to 1. When the app is switched to the foreground, the total unread count of the session is 1. If another message is received, the total unread count of the session becomes 2. When the app switches to the background again, you call the iOS system method to assign a value of 2 to the badge.

Example:

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

If the app has unreads messages from other sources except CommsEase, the badge value must be the sum of unread counts from CommsEase and other sources. Since the unread count on the CommsEase server is the unread count of messages, the unread count of new push notifications from other sources may not be added to the badge.

In this case, the unread count of all sources is required to sent to the server.

Prototype

objc@protocol NIMApnsManager <NSObject>
/**
 *  Register the callback for getting the number of badges
 *
 *  @param handler callback for getting the badge
 */
- (void)registerBadgeCountHandler:(NIMBadgeHandler)handler;
@end

Register this callback function after initializing the SDK ([[NIMSDK sharedSDK] registerWithOption:option]). The callback returns the number of badge as a global variable. You can reassign the value of this variable. The SDK automatically read the return value and send the value to the CommsEase server.

Limit of unread count on the badge

You can set the upper limit of the unread messages on the app badge if the push notifications are sent from the CommsEase platform. Go to CommsEase console > Application > IM Pro/IM Free > Settings > Set the upper limit of the unread messages on the badge.

Ringtone for push notifications

The ringtone used to alert push notifications can be customized. Similar to the payload of push notifications, you can add a key-value pair in NIMMessage - apnsPayload using sound as key. Pay attention to the format of the audio used for the ringtone. For more information, see Notifications in Your App.

Example

objcNIMMessage *message = [[NIMMessage alloc] init];
message.text = @"Sample message";
message.apnsContent = @" sent a message.";
message.apnsPayload = @{@"sound":@"message.wav"};

Set the title of a push notification

You can set the title of a push notification sent by the APNs push service from the CommsEase platform using the following two methods.

  • Set the values to the title and body in NIMMessage - apnsPayload - apsField - alert to specify the title and body of a push notification. This method has the highest priority. The title and/or body of a push notification are empty if the alert field of apsField is specified with the title and/or body keys having an empty value or the key-value pair not configured. See the following example for details.
  • If the title is not configured in apsField and "pushTitle":"title" is configured in the payload, the title will be displayed (highest priority).
  • If no title of a push notification is configured, the title will not be displayed.

You cannot configure the aps field in the payload. IM allows you to set the apsField field in payload, which corresponds to the aps field in the payload of APNs. This field is only available for iOS apps and Android apps cannot parse this field. The following shows the payload with the apsField field:

json{
    // The sample code is formatted for demo purposes, do not format the data for actual use.
    "key1": "value1", //custom key-value pair
    "apsField": {
        "mutable-content": 1,
        "sound": "abc.wav",
        "alert": {
            "title": "Title",
            "body": "Body of a push notification"
        },
        "key2": "value2"
    }
}

Push group messages

You can also send group messages with the push service by configuring the apnsMemberOption field in NIMMessage. Recipients can still receive the message even if the current session is blocked (such as Do Not Disturb).

objc@interface NIMMessageApnsMemberOption : NSObject
/**
*  APNs for specified users. This value of nil indicates push notifications are delivered to all users in the session.
*/
@property (nullable, nonatomic, copy) NSArray<NSString*> *userIds

/**
* The default value is YES. If the value is set to YES, push notifications will be delivered users even if the users in the list mute the current session.
*/
@property (nonatomic, assign) BOOL forcePush

/**
* The content of a push notification can contain up to 500 characters
*/
@property (nullable, nonatomic, copy) NSString *apnsContent
@end

Redirects from the notification bar

If you click the notification bar to direct to the specified chat interface after receiving a push notification delivered by the APNs push, see the following solution:

When constructing a message object, the sender must insert information representing the session identifier (such as sender’s account, group ID, and session type) in NIMMessage - apnsPayload, so that the client can parse the payload when recipients receive the notification. For example:

json{
    // The sample code is formatted for demo purposes, do not format the data for actual use.
    "sessionid": "zhangsan", //The account of a sender or group ID to which the message belongs
    "sessiontype": "p2p", //The session type, a P2P chat or group chat.
    "apsField": {
        "mutable-content": 1,
        "sound": "abc.wav",
        "alert": {
            "title": "Title",
            "body": "Body of a push notification"
        },
        "key2": "value2"
    }
}

Clients receives the notification sent by the APNs push and parses APNs - payload to get sessionid and sessiontype, and directs you to the corresponding interface.

Overwrite notifications

Devices with iOS 10 and later allows the brief content displayed on the notification bar to be overwritten.The latter notifications overrides the previous push notifications. A typical scenario is the case of deleting a message:

For example, User A sends a message to B and triggers the APNs push. The message body is "Hello". User A unsends the message, and the message body "Hello" displayed on the notification bar is replaced by the preset message "A message was unsent".

Implementation: You can go to CommsEase console-Application-Settings -Unsending message-whether the unsent message overwrites the original message.

Was this page helpful?
Yes
No
  • Prerequisites
  • Create a certificate signing request
  • Create App ID
  • Enable APNS
  • Configure the certificate
  • Export the p12 file
  • Upload the certificate
  • Client configuration
  • Set the push certificate
  • Upload devicetoken
  • Do-Not-Disturb
  • Multi-device alerts**
  • Configure the push service
  • Whether the push service is enabled for messages
  • Set the body of a push notification
  • Set the head of a push notification
  • Unread count badge
  • Assign the unread count
  • Limit of unread count on the badge
  • Ringtone for push notifications
  • Set the title of a push notification
  • Push group messages
  • Redirects from the notification bar
  • Overwrite notifications