Chat SDKs iOS v3
Chat SDKs iOS
Chat SDKs
iOS
Version 3
Sendbird Chat SDK v3 for iOS is no longer supported as a new version is released. Check out our latest Chat SDK v4

Push notifications

Copy link

A push notification is a message which is immediately delivered to a user's device when the device is either idle or running the client app in the background. Push notifications for iOS client apps are sent using Apple Push Notification service (APNs), which contains custom data that your app needs in order to respond to the notifications. When a message is sent to Sendbird server through our Chat SDK for iOS, the server communicates with APNs, and then APNs delivers a push notification to an iOS device where the client app is installed.

Note: By default, when a user to receive messages is being disconnected from Sendbird server, the server sends notification requests to APNs for the messages. The Chat SDK for iOS automatically detects when a user's client app goes into the background from the foreground, and updates the user's connection status to disconnected. Therefore, in normal cases, you don't need to explicitly call the disconnectWithCompletionHandler: method.

Notifications can also be configured to display an alert, play a sound, or badge your app’s icon and are only applicable to group channels. They can't be applied to an open channel or a supergroup channel due to the massive number of users and messages.

Push notifications support both single and multi-device users and they are delivered only when a user is fully offline from all devices even when they use only one device. In other words, if a user is online on one or more devices, notifications aren't delivered and thus not displayed on any devices.

Additional multi-device support for push notifications is also provided. If selected from your dashboard, for multi-device users, notifications are delivered to all online and offline devices. However, through iOS, notifications are displayed only on offline devices.

Note: Depending on how you implement a client app, push notifications can be displayed even when the app is in the foreground, given that additional multi-device support for push notifications is selected in your dashboard. Refer to Apple Developer Documentation to learn how.

This page describes how to obtain iOS and APNs credentials from the Apple Developer portal and how to implement our push notifications in your iOS client app.


How to register push notification credentials

Copy link

The following steps explain how to download your push notification credentials for APNs and register them to the Sendbird Dashboard.

Step 1 Create your certificate signing request

Copy link

Note: Before you begin, you should already have an app ID assigned to a client app.

To obtain a signing certificate required to sign apps for installation on iOS devices, you should first create a certificate signing request (CSR) file through Keychain Access on your Mac.

  1. Open the Keychain Access from the Utilities folder, go to Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority, and then click.
  2. The Certificate Information dialog box appears. Enter the email address that you use in your Apple Developer account, and enter a common name for your private key. Don't enter CA email address, choose Saved to disk, and then click the Continue button.
  3. Specify the name of your CSR to save and choose the location to save the file on your local disk. Then your CSR file is created, which contains a public/private key pair.

Step 2 Create your push notification SSL certificate

Copy link
  1. Sign in to your account at the Apple Developer Member Center and choose Certificates, Identifiers & Profiles. In the Identifiers > App IDs, select the Push Notifications service, and then click the Configure button.
  2. When prompted by a pop-up window, choose which SSL certificate to create either Development or Production.
  3. In the Certificates, Identifiers & Profiles pane that appears after the selection, under Upload a Certificate Signing Request, upload the CSR file you created through the Choose File button. Then to complete the process, click the Continue button above. When the certificate is ready, choose Download to save it to your Mac.
  4. In order to install the downloaded certificate to the Keychain Access on your Mac, double-click it. You can find the certificate in the Keychain Access > login > Certificates.

Step 3-1 Export a .p12 file and upload to Sendbird Dashboard

Copy link

Sendbird server needs to use some of your confidential information in your .p12 file to communicate with and send notification requests to APNs on behalf of your server. A .p12 file is a set of certificates that you generated when building a client app for iOS.

Note: Now you can use a .p8 file to communicate with APNs and register it in the Sendbird Dashboard. See Step 3-2: Export a .p8 file and upload to Sendbird Dashboard for more information.

You can register your .p12 file to Sendbird server through your dashboard or by using the Chat API's add an APNs push configuration action. The following steps show how to register a .p12 file in the Dashboard.

  1. Open Keychain Access and go to login > Certificates. Find the push notification SSL certificate you just added, right-click the certificate, and then select Export "YOUR_PROJECT_NAME" from the context menu to get a .p12 file that contains the certificate.
  2. Type a name for the .p12 file and save it to your Mac. Do not provide an export password when prompted. Then sign in to your dashboard and upload the file under Settings > Chat > Notifications.
  3. When a dialog opens up, select .p12 for Format. Then click the Choose file and select your .p12 certificate to upload. Once the file is uploaded, a password box appears. If needed, you can also set a password for the file.

Step 3-2 Export a .p8 file and upload to Sendbird Dashboard

Copy link

Sendbird server needs to use some of your confidential information in your .p8 file to send notification requests to APNs on behalf of your server. A .p8 file is an authentication token that is generated when you build a client app for iOS.

You can register your .p8 file to Sendbird server through the Sendbird Dashboard or by using the platform API’s add an APNs push configuration action. The following steps show how to register a .p8 file in the dashboard.

Note: To learn more about the authentication token with a .p8 extension, visit Apple Developer's Documentation on a token-based connection to APNs.

  1. Log into your Apple Developer account and go to Certificates, Identifiers & Profiles > Keys. Then click Create a key.
  2. Once an authentication key is created, register the key with a key name of your choice and select a service you want to use. In this case, check Apple Push Notifications service (APNs) in the table. Then click Continue.
  3. Make sure the key name and service chosen are correct. Then click Register.
  4. Once the key is registered, you can download the key as a file with a .p8 extension. Download the file so that you can add it to the Sendbird Dashboard.

Note: The file can be only downloaded once. Make sure to remember the directory where your file is downloaded.

  1. Sign in to your Sendbird Dashboard and upload the file under Settings > Chat > Notifications.
  2. When a dialog opens up, select .p8 for Format. Then click Choose file and select your .p8 key file to upload. Once the file is uploaded, select SSL certificate type between Production and Developer.

Step 4 Register a device token to Sendbird server

Copy link

When requested to send notifications to a specific client app on an iOS device, APNs requires the app instance's unique device token which has been issued by the notification service. Therefore, to send notification requests to APNs on behalf of your server, Sendbird server needs every device tokens of your client app instances. If an app instance is successfully registered to APNs via the registerForRemoteNotifications method, a device token is passed to an app delegate object's application:didRegisterForRemoteNotificationsWithDeviceToken: method which is called by the app. Like the following sample code, you should register this token to Sendbird server by passing it as an argument to a parameter in the registerDevicePushToken:unique:completionHandler: method.

Note: A user can have up to 20 APNs device tokens. The oldest token will be deleted before a new token is added for a user who already has 20 device tokens. Only the 20 newest tokens will be maintained for users who already have more than 20.

When requested to send notifications to a specific client app on an iOS device, APNs requires the app instance's globally-unique and app-specific device token which has been issued by itself. Therefore, to send notification requests to APNs on behalf of your server, Sendbird server needs every device tokens of your client app instances. If an app instance is successfully registered to APNs via the registerForRemoteNotifications method, a device token is passed to an app delegate object's application:didRegisterForRemoteNotificationsWithDeviceToken: method which is called by the app. Like the following sample code, you should register this token to Sendbird server by passing it as an argument to a parameter in the registerDevicePushToken:unique:completionHandler: method.

SwiftObjective-C
// AppDelegate.swift
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // Register a device token to Sendbird server.
    SBDMain.registerDevicePushToken(deviceToken, unique: false, completionHandler: { (status, error) in
        if error == nil {
            // A device token is successfully registered.
        }
        else {
            if status == SBDPushTokenRegistrationStatus.pending {
                // A token registration is pending.
                // If this status is returned, invoke the registerDevicePushToken:unique:completionHandler: with [SBDMain getPendingPushToken] after connection.
            }
            else {
                // Handle registration failure.
            }
        }
    })
}

Note: If SBDPushTokenRegistrationStatusPending is returned through the completionHandler:, this means that your user is not being connected to Sendbird server when the registerDevicePushToken:unique:completionHandler: is called. In this case, we recommend that you first get a pending device token by using the getPendingPushToken, and then register the token by invoking the registerDevicePushToken:unique:completionHandler: in a callback of the connectWithUserId:completionHandler: or connectWithUserId:accessToken:completionHandler: when your user has been connected to the server afterward.

SwiftObjective-C
SBDMain.connect(withUserId: USER_ID, completionHandler: { (user, error) in
    if error == nil {
        SBDMain.registerDevicePushToken(SBDMain.getPendingPushToken()!, unique: false, completionHandler: { (status, error) in

        })
    }
})

Make sure you call the following code in the appropriate place to receive permissions from your users.

SwiftObjective-C
let notificationSettings = UIUserNotificationSettings(types: [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound], categories: nil)
    UIApplication.shared.registerUserNotificationSettings(notificationSettings)
    UIApplication.shared.registerForRemoteNotifications()

Step 5 Handle a notification payload

Copy link

Sendbird server sends notification requests to APNs with the following options:

OptionDescription

alert

{sender's nickname}: {text message}

sound

The default alert sound of iOS

badge

The total number of each user's unread messages. You can turn off this badge count from your dashboard.

The server also sends an additional JSON object with the sendbird key. For notification requests, APNs then delivers notifications to iOS devices. At the client side, you can parse the data payload and handle the result to implement user reactions within the application:didReceiveRemoteNotification:fetchCompletionHandler: method, which covers all notifications from the application states of inactive, foreground, and background.

SwiftObjective-C
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    let alertMsg = (userInfo["aps"] as! NSDictionary)["alert"] as! NSDictionary
    let payload = userInfo["sendbird"] as! NSDictionary

    // Implement your custom way to parse payload
    if (application.applicationState == .inactive) {
        // Receiving a notification while your app is inactive.
    } else {
        // Receiving a notification while your app is in either foreground or background.
    }

    completionHandler(UIBackgroundFetchResult.newData)
}

The following is a complete payload format of the sendbird object, which contains a set of provided key-value items. As for the channel_unread_count, the attribute can be added into or removed from the payload under Settings > Chat > Notifications in the Sendbird Dashboard.

{
    "category": "messaging:offline_notification",
    "type": string,                 // Message type: 'MESG', 'FILE', or 'ADMM'
    "message": string,              // User input message
    "data": string,                 // Custom data field
    "custom_type": string,          // Custom message type
    "message_id": long,             // Message ID
    "created_at": long,             // 13-digit timestamp
    "app_id": string,               // Application's unique ID
    "unread_message_count": int,    // Total number of new messages unread by the user
    "channel": {
        "channel_url": string,      // Group channel URL
        "name": string,             // Group channel name
        "custom_type": string       // Group channel custom_type
    },
    "channel_type": string,         // The value of "channel_type" is set by the system.
                                    // The 'messaging' indicates a distinct group channel
                                    // while 'group_messaging' indicates a private group channel
                                    // and 'chat' indicates all other cases.
    "sender": {
        "id": string,               // Sender's unique ID
        "name": string,             // Sender's nickname
        "profile_url": string       // Sender's profile image URL
    },
    "recipient": {
        "id": string,               // Recipient's unique ID
        "name": string              // Recipient's nickname
    },
    "files": [],                    // If a message is a file link,
                                    // this array represents files.
    "translations": {},             // If a message has translations,
                                    // this dict has locale:translation.
    "push_title": string,           // Title of a notification message that can be
                                    // customized in the Sendbird Dashboard
                                    // with or without variables
    "push_sound": string,           // The location of a sound file for notifications
    "audience_type": string,        // The type of audiences to receive notifications
    "mentioned_users": {
        "user_id": string,                      // The ID of a mentioned user
        "total_unread_mention_count": int,      // The number of messages which
                                                // a user has been mentioned
                                                // but has not read within the channels
        "channel_unread_mention_count": int,    // The number of channels with messages
                                                // which a user has been mentioned
                                                // but has not read
        "is_hidden": boolean                    // Whether or not a mentioned user has
                                                // hidden the channel from the list
    },
    "channel_unread_count": int // Total number of unread new messages
                                // from the specific channel
}

Step 6 Enable multi-device support in the Dashboard

Copy link

After the above implementation is completed, choose your push notification option depending on how much support for multi-device push the client app requires. Go to Settings > Application > Notifications > Push notifications for multi-device users in your dashboard.

To find out which push notifications best suits the client app use cases, refer to the table below:

Send when all devices are offlineSend as long as one device is offline

Single-device user

Displayed when disconnected from the server and thus offline

Displayed when disconnected from the server and thus offline

Multi-device user

Displayed only when all devices are offline

Displayed on all offline devices, regardless of whether one or more are online

Note: For iOS client apps, no additional implementation is required to enable multi-device support. However, for Android client apps, additional implementation is required to enable multi-device support. To learn more, go to the Android's Multi-Device Support page.


Notification preferences

Copy link

By registering or unregistering the current user's device token to Sendbird server like the following, you can turn push notifications on or off in the user's client app.

Note: The registration and unregistration methods in the code below should be called after a user has established a connection with Sendbird server via the connection methods such as connectionWithUserId:completionHandler: or connectionWithUserId:accessToken:completionHandler:.

SwiftObjective-C
func setPushNotification(enable: Bool) {
    if enable {
        SBDMain.registerDevicePushToken(SBDMain.getPendingPushToken()!, unique: false, completionHandler: { (status, error) in
            guard error == nil else {
                // Handle error.
            }


        })
    }
    else {
        // If you want to unregister the current device only, invoke this method.
        SBDMain.unregisterPushToken(SBDMain.getPendingPushToken()!, completionHandler: { (response, error) in
            guard error == nil else {
                // Handle error.
            }


        })

        // If you want to unregister the all devices of the user, invoke this method.
        SBDMain.unregisterAllPushToken(completionHandler: { (response, error) in
            guard error == nil else {
                // Handle error.
            }


        })
    }
}

The SBDPushTriggerOption allows users to configure when to receive notifications as well as what type of messages will trigger notifications. This provides the following three options:

OptionDescription

SBDPushTriggerOptionAll

When disconnected from Sendbird server, the current user receives notifications for all new messages including messages the user has been mentioned in.

SBDPushTriggerOptionMentionOnly

When disconnected from Sendbird server, the current user only receives notifications for messages the user has been mentioned in.

SBDPushTriggerOptionMentionOff

The current user doesn't receive any notifications.

SwiftObjective-C
// If you want to trigger notifications only when the current user is mentioned in messages.
SBDMain.setPushTriggerOption(.mentionOnly, completionHandler: { (error) in
    if error != nil {
        // Handle error.
    }


})

The SBDGroupChannelPushTriggerOption also allows users to configure the trigger for notifications as well as turn on or off notifications for each channel. This provides the following three options:

OptionDescription

SBDPushTriggerOptionDefault

The current user’s push notification trigger settings are automatically applied to the channel. This is the default setting.

SBDPushTriggerOptionAll

When disconnected from Sendbird server, the current user receives notifications for all new messages in the channel including messages the user has been mentioned in.

SBDPushTriggerOptionMentionOnly

When disconnected from Sendbird server, the current user only receives notifications for messages in the channel the user has been mentioned in.

SBDPushTriggerOptionOff

The current user doesn't receive any notifications in the channel.

SwiftObjective-C
// If you want to automatically apply the user's push notification setting to the channel.
channel.setMyPushTriggerOption(.default, completionHandler: { (error) in
    guard error == nil else {
        // Handle error.
    }


})

If you want to routinely turn off push notification on the current user's client app according to a specified schedule, use our Do Not Disturb feature like the following.

Note: Do Not Disturb can also be set for a user with our Chat Platform API's update push notification preferences action.

SwiftObjective-C
// The current user will not receive notifications during the specified time of every day.
SBDMain.setDoNotDisturbWithEnable(true, startHour: START_HOUR, startMin: START_MIN, endHour: END_HOUR, endMin: END_MIN, timezone: TIMEZONE, completionHandler: { (error) in
    guard error == nil else {
        // Handle error.
    }


})

To snooze notifications for specific period of time, use our snooze feature like the following.

Note: snooze can also be set for a user with our Chat Platform API's update push notification preferences action.

SwiftObjective-C
// The current user will not receive notifications during the specified period of time (from START_TS to END_TS).
SBDMain.setSnoozePeriodEnable(true, startTimestamp: START_TS, endTimestamp: END_TS, completionHandler: { (error) in
    guard error == nil else {
        // Handle error.
    }


})

Push notification content templates

Copy link

Push notification content templates are pre-formatted forms that can be customized to display your own push notification messages on a user’s device. Sendbird provides two types: default and alternative. Both templates can be customized from your dashboard by going to Settings > Chat > Notifications > Push notification content templates.

Content templates

Copy link

There are two types of push notification content template: Default and Alternative. Default template is a template that applies to users with the initial notification message setting. Alternative template is used when a user selects a different notification content template instead of the default template.

The content in the template is set at the application level while the selection of templates is determined by a user or through the Platform API.

Note: When a custom channel type has its own customized push notification content template, it takes precedence over the default or alternative templates.

Both templates can be customized using the variables of sender_name, filename, message, channel_name, and file_type_friendly which will be replaced with the corresponding string values. As for the file_type_friendly, it will indicate the type of the file sent, such as Audio, Image, ans Video.

Refer to the following table for the usage of content templates:

Text messageFile message

Default template

{sender_name}: {message} (ex. Cindy: Bye!)

{filename} (ex. hello_world.jpg)

Alternative template

New message arrived

New file arrived

To apply a template to push notifications, use the setPushTemplateWithName:completionHandler: method. Specify the type of the template with the name as either SBD_PUSH_TEMPLATE_DEFAULT or SBD_PUSH_TEMPLATE_ALTERNATIVE.

SwiftObjective-C
SBDMain.setPushTemplateWithName(SBD_PUSH_TEMPLATE_ALTERNATIVE, completionHandler: { (error) in
    guard error == nil else {
        // Handle error.
    }

    // Push template successfully set to SBD_PUSH_TEMPLATE_ALTERNATIVE.
})

You can check the current user's setting with getPushTemplateWithCompletionHandler: like the following:

SwiftObjective-C
SBDMain.getPushTemplate(completionHandler: { (name, error) in
    guard error == nil else {
        // Handle error.
    }

    if name == SBD_PUSH_TEMPLATE_DEFAULT {
        // Currently configured to use the default template.
    }
    else if name == SBD_PUSH_TEMPLATE_ALTERNATIVE {
        // Currently configured to use the alternative template.
    }
})

Push notification tester

Copy link

After registering a credential for push notification services, you can test whether push notification credentials and notification services work properly through the Sendbird Dashboard.

In Settings > Notifications > Push notification credentials on the dashboard, each credential has a Send button that allows you to send a test message. The test message will be sent to a target user and their device, which sets off a push notification on the device. At the same time, a new group channel will be created for this test, containing only the target user. If you've already tested push notification with the same target user and the same target device token, the message will be sent to the existing test channel.

Note: If there is another member in the test channel or the target user has left the channel, delete the test channel before carrying out a test.

  1. Go to Settings > Notifications > Push notification credentials on Sendbird Dashboard. Find a Send button in the right-end column of each table.

  1. You can search a target user by either their User ID or Nickname in the popup window. Once a user is selected, choose a target device from a list of device tokens linked to the user.

  1. Double check to see if you've selected a correct device token of the user because this push notification will show up on an actual mobile device. Confirm the target channel name and URL, then send the message.

Note: If this is your first test, a new test channel will be created. For future tests with the same target user and the same target device token, the name and URL of the existing test channel will show above the message box.

  1. Check to see if the push notification arrived on the mobile device. The test message will state the time when Sendbird server sent the message.
Test message sent at {HH:MM:SS} on {MM-DD-YYYY}

Note: For iOS devices, only an actual mobile device can receive push notifications while emulators can't.


Push notification translation

Copy link

Push notification translation allows your users to receive notifications in their preferred languages. Users can set up to four preferred languages. If messages are sent in one of those languages, the notifications won’t be translated. If messages are sent in a language other than the preferred languages, the notifications will be translated into the user's first preferred language. In addition, the messages translated into other preferred languages will be provided in the sendbird property of a notification payload.

Note: A specific user's preferred languages can be set with our Chat API's update a user action.

Using the method as follows, the current user's preferred languages can be set:

SwiftObjective-C
SBDMain.connect(withUserId: USER_ID, completionHandler: { (user, error) in
    guard error == nil else {
        // Handle error.
    }

    let preferredLanguages = ["fr", "de", "es", "kr"] // French, German, Spanish, and Korean

    SBDMain.updateCurrentUserInfo(withPreferredLanguages: preferredLanguages, completionHandler: { error in
        guard error == nil else {
            // Handle error.
        }

        var isUpdatedSuccessfully = true

        // The 'user' object below is the reference of the current user.
        for language in user.preferredLanguages {
            if !preferredLanguages.contains(language) {  // The user.preferredLanguages returns a list of the current user's preferred languages.
                isUpdatedSuccessfully = false
                break
            }
        }

        if isUpdatedSuccessfully == true {
            // The current user's preferred languages have been updated successfully.
        }
    })
})

If successful, the following notification payload will be delivered to the current user's device.

{
    "aps": {
        "alert": "Bonjour comment allez vous",  // A notification is translated into the first language listed in the preferred languages.


    },
    "sendbird": {
        "category": "messaging:offline_notification",
        "type": "User",
        "message": "Hello, how are you?",


        "translations": {   // The translated messages in other preferred languages.
            "fr": "Bonjour comment allez vous",
            "de": "Hallo wie geht es dir",
            "es": "Hola como estas",
            "kr": "안녕하십니까?"
        },


    }
}