Business Messaging Client Side v2
Business Messaging
Version 2

Push notifications for UIKit

Copy link

Push notifications are messages that are sent to a user's device from a server. They can be used to notify users of new messages, updates, or other important information. In this guide, we'll show you how to implement push notifications in your client app when using the Business Messaging UIKit.


Android

Copy link

Push notification messages for Android devices will be delivered through Firebase Cloud Messaging service. There are two types of FCM messages: notification messages and data messages. Sendbird uses data messages, which are handled by the client app. They allow users to customize the message payload, which consists of key-value items.

The following is a set of step-by-step instructions on how to set up push notifications for FCM.

Note: See Push notifications for HMS if you want to see the instructions for HMS push notifications. For Business Messaging, use authenticate() instead of connect() in the code snippets.

Step 1 Generate private key for FCM

Copy link

The Sendbird server requires your private key to send notification requests to FCM on behalf of your server. This is required for FCM to authorize HTTP requests.

Note: If you already have your private key, skip this step and go directly to Step 2: Register private key to Sendbird Dashboard.

  1. Go to the Firebase console. If you don't have a Firebase project for a client app, create a new project.

  1. Select your project card to move to the Project Overview.

  2. Click the gear icon at the upper left corner and select Project settings.

  1. Go to Service accounts and click on Generate a new private key.

  1. Go to the General tab and select your Android app to add Firebase to. During the registration process, enter your package name, download the google-services.json file, and place it in your Android app module root directory.

Step 2 Register private key to Sendbird Dashboard

Copy link

Register your private key to the Sendbird server through the dashboard as follows.

  1. Sign in to your dashboard and go to Settings > Application > Push notifications.

  2. Turn on Push notifications and select Send when all devices are offline.

  3. Scroll down to the FCM section and click on Add credentials.

  1. Under Service account key (HTTP v1), upload the JSON file containing the key that was downloaded in Step 1.

Note: Your private key can also be registered using our add an FCM push configuration API.

Step 3 Set up an FCM client app on your Android project

Copy link

In your root-level (project-level) Gradle file ({project}/build.gradle.kts or {project}/build.gradle), add the Google services plugin as a dependency:

Note: The firebase-messaging version should be 19.0.1 or higher.

build.gradle.ktsbuild.gradle
plugins {
  id("com.android.application") version "7.3.0" apply false
  // ...

  // Add the dependency for the Google services Gradle plugin
  id("com.google.gms.google-services") version "4.4.2" apply false
}

In your module (app-level) Gradle file (usually {project}/{app-module}/build.gradle.kts or {project}/{app-module}/build.gradle), add the Google services plugin:

build.gradle.ktsbuild.gradle
plugins {
  id("com.android.application")

  // Add the Google services Gradle plugin
  id("com.google.gms.google-services")
  // ...
}

In your module (app-level) Gradle file (usually {project}/{app-module}/build.gradle.kts or {project}/{app-module}/build.gradle), add the firebase-messaging dependency for the in your app.

build.gradle.ktsbuild.gradle
dependencies {
  // ...

  implementation("com.google.firebase:firebase-messaging:33.2.0")
}

Note: To learn more about this step, refer to Firebase's Set Up a Firebase Cloud Messaging client app on Android guide. The Google FCM sample project is another helpful reference.

Step 4 Register a registration token to the Sendbird server

Copy link

The following classes and interface are provided to implement push notifications.

Class or interfaceDescription

SendbirdPushHandler

A class that provides the onNewToken() and onMessageReceived() callbacks as well as other callbacks to handle a user's registration token and receive notification messages from FCM.

SendbirdPushHelper

A class that provides the methods to register and unregister a SendbirdPushHandler handler, check if the same message has already been received, and more.

OnPushTokenReceiveListener

An interface that contains the onReceived() callback to receive a user's registration token from FCM.

class MyFirebaseMessagingService : SendbirdPushHandler() {
    // This is invoked when a notification message has been delivered to the current user's client app.
    override fun onMessageReceived(context: Context, remoteMessage: RemoteMessage) {
        try {
            val pushTitle = remoteMessage.data["push_title"]
            val message = remoteMessage.data["message"]
            val payload = remoteMessage.data["sendbird"] ?: return
            val sendbirdJson = JSONObject(payload)
            val channelJson = sendbirdJson.getJSONObject("channel")
            val channelUrl = channelJson.getString("channel_url")

            // If you want to customize a notification with the received FCM message,
            // write your method like sendNotification() below.
            sendNotification(context, pushTitle, message, channelUrl)
        } catch (e: JSONException) {
            e.printStackTrace()
        }
    }

    fun sendNotification(context: Context, messageTitle: String?, messageBody: String?, channelUrl: String) {
        // Customize your notification containing the received FCM message.
    }
}

Note: Upon initial startup of your app, the FCM SDK generates a unique and app-specific registration token for the client app instance on your user's device. FCM uses this registration token to determine which device to send notification messages to.

In order to receive information about push notification events for the current user from Sendbird server, register a MyFireBaseMessagingService instance to SendbirdPushHelper as an event handler. It is recommended to register the instance in the onCreate() method of the Application instance as follows:

class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
        // SendbirdUIKit.init
        
        // It must be called after calling SendbirdUIKit.init
        SendbirdPushHelper.registerHandler(MyFirebaseMessagingService())
    }
}

Also, register a MyFireBaseMessagingService instance when a user logs into Sendbird server as follows:

SendbirdUIKit.authenticate { user, e ->
    if (e != null) {
        // Handle error.
    }
    ...

    SendbirdPushHelper.registerHandler(MyFirebaseMessagingService())
}

The instance should be unregistered when a user logs out from Sendbird server as follows:

SendbirdPushHelper.unregisterHandler(
    IS_UNREGISTER_ALL,
    object : SendbirdPushHelper.PushRequestCompleteListener {
        override fun onComplete(isRegistered: Boolean, token: String?) {
            SendbirdChat.disconnect {
                // Clear user-related data.
            }
        }

        override fun onError(e: SendbirdException) {
            // Handle error.
        }
    }
)

Step 5 Handle an FCM message payload

Copy link

The Sendbird server sends push notification payloads as FCM data messages, which contain notification-related data in the form of key-value pairs. Unlike notification messages, the client app needs to parse and process these data messages in order to display them as local notifications.

The following code shows how to receive a push notification payload and parse it as a local notification. The payload consists of two properties: message and sendbird. The message property is a string generated according to a push notification template you set on the Sendbird Dashboard. The sendbird property is a JSON object which contains all the information about the message a user has sent. Within MyFirebaseMessagingService.kt, you can show the parsed messages to users as a notification using your custom sendNotification() method.

Note: See Firebase’s Receive messages in an Android app guide to learn more about how to implement code to receive and parse a FCM notification message, how notification messages are handled depending on the state of the receiving app, how to edit the app manifest, or how to override the onMessageReceived method.

override fun onMessageReceived(remoteMessage: RemoteMessage) {
    try {
        if (remoteMessage.getData().containsKey("sendbird")) {
            val sendbird = JSONObject(remoteMessage.getData().get("sendbird"))
            val channel = sendbird.get("channel") as JSONObject
            val channelUrl = channel["channel_url"] as String
            val messageTitle = sendbird.get("push_title") as String
            val messageBody = sendbird.get("message") as String
            // If you want to customize a notification with the received FCM message,
            // write your method like sendNotification() below.
            sendNotification(context, messageTitle, messageBody, channelUrl)
        }
    } catch (e: JSONException) {
            e.printStackTrace()
    }
}
// ...

fun sendNotification(
    context: Context,
    messageTitle: String,
    messageBody: String,
    channelUrl: String
) {
    // Implement your own way to create and show a notification containing the received FCM message.
    val notificationBuilder = NotificationCompat.Builder(context, channelUrl)
        .setSmallIcon(R.drawable.img_notification)
        .setColor(Color.parseColor("#7469C4")) // small icon background color
        .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.drawable.logo_sendbird))
        .setContentTitle(messageTitle)
        .setContentText(messageBody)
        .setAutoCancel(true)
        .setSound(defaultSoundUri)
        .setPriority(Notification.PRIORITY_MAX)
        .setDefaults(Notification.DEFAULT_ALL)
        .setContentIntent(pendingIntent)
}

The following is a complete payload format of the sendbird property, which contains a set of provided key-value items. Some fields in the push notification payload can be customized in Settings > Chat > Notifications on the Sendbird Dashboard. For example, push_title and push_alert are created based on the Title and Body text you set in Push notification content templates, respectively, in the Notifications menu. In order to display them in a local notification, pass push_title and push_alert of the push notification payload into the setContentTitle and setContentText methods of the NotificationCompat.Builder class, respectively. Also, the channel_unread_count field can be added into or removed from the payload in the same menu on the Sendbird Dashboard.

{
    "category": "messaging:offline_notification",
    "type": string,                         // Message type: MESG, FILE, or ADMM
    "message": string,                          // User input message
    "custom_type": string,                  // Custom message type
    "message_id": long,                      // Message ID
    "created_at": long,                      // The time that the message was created, in a 13-digit Unix milliseconds format
    "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,           // Custom Group channel type
        "channel_unread_count": int // Total number of unread new messages from the specific channel
    },
    "channel_type": string,             // A value of channel_type is set by the system. The value of 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
        "require_auth_for_profile_image": false,
        "metadata": {}
    },
    "recipient": {
        "id": string,                            // Recipient's unique ID
        "name": string                          // Recipient's nickname
    },
    "files": [],                            // An array of data regarding the file message, such as filename
    "translations": {},                      // The items of 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 for notifications
    "mentioned_users": {
        "user_id": string,              // The ID of a mentioned user
        "nickname": string,         // The nickname of a mentioned user
        "profile_url": string,      // Mentioned user's profile image URL
        "require_auth_for_profile_image": false
    },
}

Push notification messages for iOS devices will be delivered through Apple Push Notification service (APNs). To notify users of events that take place on a client app, you should register your APNs notification credentials first. The following steps explain how to download your push notification credentials for APNs and register them to the Sendbird server via your dashboard.

Step 1 Create your certificate signing request

Copy link

To set up push notifications on a client app, have an app ID assigned to your 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 Keychain Access from the Utilities folder, go to Keychain Access > Certificate Assistant, and then click Request a Certificate From a Certificate Authority.

  1. When 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.

  1. 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.

  1. When prompted by a pop-up window, choose which SSL certificate to create either Development or Production.

  1. 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.

  1. 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

The 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 the 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.

  1. 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 > Push notifications.

  1. 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.

  2. Then enable Mutable content in the Extensions section. Finally, click Add.

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

Copy link

The 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 the 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.

  1. 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.

  1. Make sure the key name and service chosen are correct. Then click Register.

  1. 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 > Push notifications.

  1. 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 and enable Mutable content in the Extensions section. Then click Add.

Step 3-3: Enable the push notifications capability in Xcode

Copy link

To use remote push notifications in your app's xcode project, you need to enable the push notifications capability.

For more information, follow the steps in the Enable the Push Notifications Capability section of Apple's Registering Your App with APNs article.

Step 4 Register a device token to the Sendbird server

Copy link

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, the Sendbird server needs every device token 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 the 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. If a user already has 20 device tokens, the oldest token will be deleted before a new token is added. Only the 20 newest tokens will be maintained for users who already have more than 20.

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    // ...
    func application(_ application: UIApplication,
                     didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // Register a device token to SendBird server.
        SendbirdUI.registerPush(deviceToken: deviceToken) { success in
            
        }
    }
    // ...
}

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

let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.sound, .alert, .badge]) { granted, error in
    DispatchQueue.main.async {
        UIApplication.shared.registerForRemoteNotifications()
    }
}

Step 5 Handle a notification payload

Copy link

The 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.

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 codes to parse payload.
    if (application.applicationState == .inactive) {
        // Receive a notification while your app is inactive.
    } else {
        // Receive 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 channel_unread_count, the attribute can be added into or removed from the payload in Settings > Chat > Push notifications on the Sendbird Dashboard.

{
    "category": "messaging:offline_notification",
    "type": string,                 // Message type can be MESG, FILE, or ADMM.
    "message": string,              // User input message.
    "custom_type": string,          // Custom message type.
    "message_id": long,             // Message ID.
    "created_at": long,             // The time that the message was created in a 13-digit Unix milliseconds format.
    "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,       // Custom Group channel type.
        "channel_unread_count": int // Total number of unread new messages from the specific channel.
    },
    "channel_type": string,         // The value of channel_type is set by the system.
                                    // messaging indicates a distinct group channel,
                                    // while group_messaging indicates a private group channel.
                                    // 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.
        "require_auth_for_profile_image": false,
        "metadata": {}
    },
    "recipient": {
        "id": string,               // Recipient's unique ID.
        "name": string              // Recipient's nickname.
    },
    "files": [],                    // An array of data regarding the file message, such as filename.
    "translations": {},             // The items of locale:translation.
    "push_title": string,           // Title of a notification message that can be customized on the Sendbird Dashboard with or without variables.
    "push_alert": string,           // Body text of a notification message that can be customized on 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 for notifications.
    "mentioned_users": {
        "user_id": string,          // The ID of a mentioned user.
        "nickname": string,         // The nickname of a mentioned user.
        "profile_url": string,      // Mentioned user's profile image URL.
        "require_auth_for_profile_image": false
    },
}

Multi-device push notification

Copy link

For those who are using Sendbird Chat in conjunction with Sendbird Business Messaging and handle user connection through WebSocket, we also support push notifications for multi-device users. After the above implementation is completed, determine whether multi-device push notification is required for your client app. To set it up, go to Settings > Chat > Push notifications > Push notifications for multi-device users on our dashboard.

The following table explains when a notification message is sent and whether it is displayed on the device depending on your notification support settings and the device' online status. Refer to the table to find out which notification support best suits the client app use cases.

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