Business Messaging Client Side v2
Business Messaging
Version 2

Install Chat UIKit for Business Messaging

Copy link

This guide demonstrates how to install Chat UIKit and render a notification message using the kit for Sendbird Business Messaging. Sendbird Chat UIKit for Business Messaging is a set of prebuilt UI components that allows you to easily craft an in-app notification channel. Our development kit includes light and dark themes, fonts, colors and more.

You can install Chat UIKit for Business Messaging on the client app to receive notifications sent through the Business Messaging API or an external platform. Currently, the UIKit for Sendbird Business Messaging are supported on Android and iOS. Follow the instructions below by platform.

Note: Sendbird Business Messaging uses the existing Chat UIKit for Android v3.5.0 and later. To learn more about Sendbird UIKit for Chat, refer to this page.


You can start building a notification channel in your app by installing Chat UIKit for Business Messaging. This developer kit is an add-on feature to Sendbird Chat SDK so installing it will also install the core Chat SDK.

Requirements

Copy link

The minimum requirements for Chat UIKit Android for Business Messaging are:

  • iOS 11.0 and later
  • Xcode 14.1 and later
  • Swift 5.0+
  • Sendbird Chat SDK for iOS 4.19.1 and later
  • Sendbird Chat UIKit for iOS 3.20.0 and later

Before you start

Copy link

Before installing Sendbird Chat SDK, you need to create a Sendbird application on Sendbird Dashboard, which comprises everything required in a chat and notification service including users, notifications, and channels. You will need the Application ID of your Sendbird application when initializing the SDK.

Note: Each Sendbird application can only be integrated with a single client app.

Step 1 Create a project

Copy link

To get started, open Xcode and create a new project. The UIKit supports swift.

Step 2 Install Chat UIKit for Business Messaging

Copy link

You can install Chat UIKit for iOS through either Swift Packages, CocoaPods, or Carthage.

Swift Packages

Copy link
  1. In Xcode, select File > Add Packages.

  2. Search for SendbirdUIKit spm repository and add it to your Package repository. You can also choose the dependency rule that you want to use in the repository and keep the latest version by selecting the main branch.

https://github.com/sendbird/sendbird-uikit-ios-spm
  1. When finished, Xcode automatically begins resolving and downloading your dependencies to the repository in the background.

Note: A build error may occur while using Swift packages with Xcode due to issues with caching. To resolve this error, try resetting the Xcode package caches. Open the File menu, go to Packages, and select Reset Package Caches. This deletes all local package data and re-downloads each package from its online source.

CocoaPods

Copy link
  1. Add SendBirdUIKit into your Podfile in Xcode as below:
platform :ios, '11.0'
use_frameworks!

target YOUR_PROJECT_TARGET do
    pod 'SendBirdUIKit' # Add this line.
end
  1. Install the SendBirdUIKit framework through CocoaPods.
$ pod install
  1. Update the SendBirdUIKit framework through CocoaPods.
$ pod update

Carthage

Copy link
  1. Add SendbirdUIKit and SendbirdChatSDK into your Cartfile as below:
github "sendbird/sendbird-uikit-ios"
github "sendbird/sendbird-chat-sdk-ios"
  1. Install the SendbirdUIKit framework through Carthage.
$ carthage update --use-xcframeworks

Note: Building or creating the SendbirdUIKit framework with Carthage can only be done using the latest Swift. If your Swift is not the most recent version, the framework should be copied into your project manually.

  1. Go to your Xcode project target's General settings tab in the Frameworks and Libraries section. Then drag and drop SendbirdUIKit.xcframework and SendbirdChatSDK.xcframework from the <YOUR_XCODE_PROJECT_DIRECTORY>/Carthage/Build folder.

Note: Errors may occur if you're building your project with Xcode 11.3 or earlier versions. To fix these errors, refer to Handle errors caused by unknown attributes.

Step 3 Initialize with APP_ID

Copy link

To integrate and run Chat UIKit for Business Messaging in your app, you need to first initialize the SendbirdUI instance through AppDelegate.

Sendbird UIKit relies on local caching and synchronization for efficient data handling. Due to local caching, the data base must be migrated during the initialization process of the SendbirdUI instance. And, the UIKit won’t advance to subsequent steps until its initialization process has been fully completed. To enhance user experience and manage expectations during this process, we recommend you implement a visual loading indicator as follows:

  • Display when startHandler is called.
  • Hide when completionHandler is called.

Note: If you wish to have the initialization run asynchronously, you can set the needsSynchronous parameter to false within InitParams of the initParamsBuilder block.

// AppDelegate.swift

import SendbirdUIKit

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    let APP_ID = "YOUR_APP_ID"    // Specify your Sendbird application ID.

    SendbirdUI.initialize(
        applicationId: APP_ID
    ) { params in
        // This is the builder block where you can modify the initParameter.
        //
        // [example]
        // params.needsSynchronous = false
    } startHandler: {
        // This is the origin.
        // Initialization of SendbirdUIKit has started.
        // We recommend showing a loading indicator once started.
    } migrationHandler: {
        // DB migration has started.
    } completionHandler: { error in
        // If DB migration is successful, proceed to the next step.
        // If DB migration fails, an error exists.
        // We recommend hiding the loading indicator once done.
    }
}

The initParamsBuilder of the initialize(applicationId:initParamsBuilder:migrationHandler:completionHandler:) function of the SendbirdUI class allows you to modify the use of local caching and the synchronization settings of the initialization task.

If you are using local caching, you can also set the needsSynchronous parameter of the InitParams object to true to ensure that the migration process is completed before the app is fully launched. By default, the needsSynchronous parameter is set to false so that migration proceeds asynchronously for reduced initialization time and thus expedited performance and runtime. However, if you don't need the UIKit's features upon launching your app, you can set the needsSynchronous parameter to true and have it run synchronously. If you aren't using local caching, this parameter doesn't affect the initialization process.

In the meantime, when you need to call one of the UIKit's functions asynchronously from a different class or method, use the executeOrWaitForInitialization(executeHandler:) method of the SendbirdChat class. This function ensures either of the following two scenarios:

  • If the SendbirdUI initialization has been completed, the function executes the executeHandler block immediately.
  • If not, the function waits until the initialization is completed and then executes the executeHandler block.

This approach allows for seamless integration of the UIKit's functionalities, ensuring that initialization dependencies are properly managed.

Swift
SendbirdChat.executeOrWaitForInitialization {
    // Implement logic to perform once initialization is complete
}

Step 4 Set current user

Copy link

User information must be set as currentUser in the SBUGlobals prior to launching Chat UIKit for Business Messaging. This information will be used for various tasks within the kit, and if you don't set currentUser in advance, there will be restrictions while using the UIKit. The userID field shown below must be specified. Other fields such as nickname and profileURL are optional, and if not specified, they'll be filled with default values.

Set currentUser for the UIKit through the AppDelegate as below:

Note: Even if you don't use AppDelegate, you should still register user information before launching a chat service.

// AppDelegate.swift

import SendbirdUIKit

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Initialize with APP_ID on Step 3

    // Case 1: USER_ID only
    SBUGlobals.currentUser = SBUUser(userId: {USER_ID})

    // Case 2: Specify all fields
    SBUGlobals.currentUser = SBUUser(userId: {USER_ID}, nickname:{(opt)NICKNAME}, profileURL:{(opt)PROFILE_URL})

}

Step 5 Set an access token

Copy link

Sendbird server authenticates requests from client apps through two methods: using only user ID or using a user ID and the user's access token.

The user ID authentication method can be useful for applications in development or for existing services where users can log in as guests without additional security. Meanwhile, the access token authentication method generates access tokens for each user through Chat API. Once you request and obtain a token, you need to use that specific access token to authenticate the user.

SBUGlobals.accessToken = {ACCESS_TOKEN}

Step 6 Connect or authenticate to Sendbird server

Copy link

There are two methods to connect to the Sendbird server: SendbirdUI.connect(completionHandler:) and SendbirdUI.authenticate(completionHandler:).

If you wish to only implement in-app channels for Business Messaging in your client app, it's highly recommended that you authenticate a user to the Sendbird server. If you're already using Chat SDK and want to additionally implement Business Messaging's in-app channels, then you should connect a user to the Sendbird server.

Connect a user

Copy link

Once the currentUser is set, you can connect the user to the Sendbird server using SendbirdUI.connect(completionHandler:). You need to call this method to connect to the Sendbird server. The SendbirdUI.connect(completionHandler:) method creates an active WebSocket connection with the server, which allows the Chat SDK to receive real-time events.

If the user ID used during the connection attempt doesn't exist on the Sendbird server, a new user account is created with the specified user ID. The SendbirdUI.connect(completionHandler:) method also automatically updates the user profile on the Sendbird server.

When the view controller is called in UIKit for Business Messaging, the connection is automatically made with the currentUser which should be already set in the SBUGlobals.

With local caching added to Sendbird Chat SDK, the latest user instance may be returned through the callback even when the user is offline. The local caching functionality stores message and channel data in the local storage and the Sendbird server. As a result, even when a user isn't connected to the server, the user information stored in the local cache is returned through the callback along with an error indicating the offline status.

Refer to the code below to see how to connect a user to the Sendbird server:

SendbirdUI.connect { (user, error) in
    guard let user = user else {
        // The user is offline and you can't access any user information stored in the local cache.
        return
    }
    if let error = error {
        // The user is offline but you can access user information stored in the local cache.
    }
    else {
        // The user is online and connected to the server.
    }
}

Authenticate a user

Copy link

Once the currentUser is set, you can authenticate the user to the Sendbird server using SendbirdUI.authenticate(completionHandler:). It's highly recommended to use this method to authenticate to the Sendbird server if you're only displaying in-app notification channel view in the client app.

When keeping your notification channels up to date, you can either create an active WebSocket connection with the server or manually refresh the channel with latest information. In this case where you're displaying a channel view by authenticating a user to the server, you need to refresh notification collections to update your channel. This is because the Chat SDK can't receive real-time events to notify the user with updated information about the channel view when there's no active WebSocket connection with the server.

In order to use the SendbirdUI.authenticate(completionHandler:) method, you must first issue a session token. After authenticating with the session token, you must set a session delegate so that the client app can renew the token upon the user's session expiration. When using SendbirdUI.authenticate(completionHandler:), all session keys are set to expire so it's important that you implement the session handler in order to keep using Sendbird Business Messaging.

Then, you can call SendbirdUI.authenticate(completionHandler:) to create a new user account or log in with an existing account with the specified user ID and session token. This method authenticates the UIKit and allows it to retrieve feed channels, display notification messages, and more. Refer to the code snippet below.

SendbirdUI.authenticate { user, error in
    // User is authenticated.
}

Note: If you use the authenticate(completionHandler:) method to connect to the Sendbird server, you can't access group channels or open channels. Error messages, such as User auth session is not allowed to use requested service., will be returned when trying to use Chat SDK's public interfaces.

Step 7 Register push notification credentials

Copy link

In order to receive push notifications, you need to register notification credentials first. Refer to this page on how to upload your push certificate and register a device token.

Step 8 Display notification channel

Copy link

Refer to the codes below to display either channel view or channel list view where you can see the notifications that were sent to the channel.

Feed view

Copy link

In order to display the in-app notification channel view, you need to first find its channel URL on Sendbird Dashboard under Business Messaging > Channels.

Implement the following code to create a view controller.

let channelVC = SBUViewControllerSet.FeedNotificationChannelViewController.init(
    channelURL: "FEED_CHANNEL_CHANNEL_URL"
)
self.navigationController?.pushViewController(channelVC, animated: true)


Android

Copy link

You can start building a notification channel in your app by installing Chat UIKit for Business Messaging. This developer kit is an add-on feature to Sendbird Chat SDK so installing it will also install the core Chat SDK.

Requirements

Copy link

The minimum requirements for Chat UIKit Android for Business Messaging are:

  • Android 5.0 (API level 21) or higher
  • Java 8 or higher
  • Support androidx only
  • Android Gradle plugin 4.0.1 or higher
  • Sendbird Chat SDK for Android 4.16.0 and later
  • Sendbird Chat UIKit for Android 3.15.0 and later

Before you start

Copy link

Before installing Sendbird Chat SDK, you need to create a Sendbird application on Sendbird Dashboard, which comprises everything required in a chat and notification service including users, notifications, and channels. You will need the Application ID of your Sendbird application when initializing the SDK.

Note: Each Sendbird application can only be integrated with a single client app.

Step 1 Create a project

Copy link

To get started, open Android Studio and create a new project for the UIKit in the Project window as follows:

  1. Click Start a new Android Studio project in the Welcome to Android Studio window.
  2. Select Empty Activity in the Select a Project Template window and click Next.
  3. Enter your project name in the Name field in the Configure your project window.
  4. Select your language as either Java or Kotlin from the Language drop-down menu.
  5. Make sure Use legacy android.support.libraries is unchecked.
  6. Select minimum API level as 21 or higher.

Step 2 Install Chat UIKit for Business Messaging

Copy link

You can install Chat UIKit for Android through Gradle. If using Gradle 6.7 or lower, add the following code to your root build.gradle file:

allprojects {
    repositories {
        maven { url "https://jitpack.io" }
        maven { url "https://repo.sendbird.com/public/maven" }
    }
}

Note: Make sure the above code block isn't added to your module build.gradle file.

If using Gradle 6.8 or higher, add the following to your settings.gradle file:

dependencyResolutionManagement {
    repositories {
        maven { url "https://jitpack.io" }
        maven { url "https://repo.sendbird.com/public/maven" }
    }
}

Note: To learn more about updates to Gradle, see Gradle's release note.

Next, for all Gradle versions, open the build.gradle file at the application level. For both Java and Kotlin, add the following code block and dependencies:

apply plugin: 'com.android.application'

android {
    buildFeatures {
        viewBinding true
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8    // Make sure you have JavaVersion 1.8.
        targetCompatibility JavaVersion.VERSION_1_8    // Make sure you have JavaVersion 1.8.
    }
}

dependencies {
    implementation 'com.sendbird.sdk:uikit:3.+'
}

Before saving the build.gradle file, check if you’ve enabled viewBinding. Then, click the Sync button to apply all changes.

Note: UIKit SDK versions 2.1.1 or lower can be downloaded from JCenter until February 1, 2022. SDK versions higher than 2.1.1 will be available on Sendbird's remote repository.

Step 3 Set an access token

Copy link

Sendbird server authenticates requests from client apps through two methods: using only user ID or using a user ID and the user's access token.

The user ID authentication method can be useful for applications in development or for existing services where users can log in as guests without additional security. Meanwhile, the access token authentication method generates access tokens for each user through Chat API. Once you request and obtain a token, you need to use that specific access token to authenticate the user and log into the client app.

JavaKotlin
SendbirdUIKit.init(new SendbirdUIKitAdapter() {
    @Override
    @NonNull
    public String getAccessToken() {
        return "ACCESS_TOKEN";
    }
}, context)

Step 4 Initialize SendbirdUIKit instance

Copy link

To integrate and run Chat UIKit for Business Messaging in your app, you need to initialize it first. You can initialize SendbirdUIKit instance by passing the SendbirdUIKitAdapter instance as an argument to a parameter in the SendbirdUIKit.init() method. The SendbirdUIKit.init() must be called once in the onCreate() method of your app’s Application instance.

Note: The UIKit uses local caching so that the client app can locally cache and retrieve channel and message data. The initialization process of the SendbirdUIKit instance is asynchronous and requires you to receive a callback function before you can move onto the next step. If the database fails to migrate, the onInitFailed() method is called. If the database successfully migrates, the onInitSucceed() method is called and you can proceed to the next step. Refer to the updated code below.

JavaKotlin
import android.app.Application;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.sendbird.uikit.SendbirdUIKit;
import com.sendbird.uikit.adapter.SendbirdUIKitAdapter;
import com.sendbird.uikit.interfaces.UserInfo;
import com.sendbird.android.handler.InitResultHandler;
import com.sendbird.android.exception.SendbirdException;

public class BaseApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        SendbirdUIKit.init(new SendbirdUIKitAdapter() {
            @NonNull
            @Override
            public String getAppId() {
                return "YOUR_APP_ID";  // Specify your Sendbird application ID.
            }

            @Nullable
            @Override
            public String getAccessToken() {
                return "";
            }

            @NonNull
            @Override
            public UserInfo getUserInfo() {
                return new UserInfo() {
                    @Override
                    public String getUserId() {
                        return "USER_ID";  // Specify your user ID.
                    }

                    @Nullable
                    @Override
                    public String getNickname() {
                        return "USER_NICKNAME";  // Specify your user nickname.
                    }

                    @Nullable
                    @Override
                    public String getProfileUrl() {
                        return "";
                    }
                };
            }

            @NonNull
            @Override
            public InitResultHandler getInitResultHandler() {
                return new InitResultHandler() {
                    @Override
                    public void onMigrationStarted() {
                        // DB migration has started.
                    }

                    @Override
                    public void onInitFailed(SendbirdException e) {
                        // If DB migration fails, this method is called.
                    }

                    @Override
                    public void onInitSucceed() {
                        // If DB migration is successful, this method is called and you can proceed to the next step.
                        // In the sample app, the LiveData class notifies you on the initialization progress
                        // And observes the MutableLiveData<InitState> initState value in SplashActivity().
                        // If successful, the LoginActivity screen
                        // Or the HomeActivity screen will show.
                    }
                };
            }
        }, this);
    }
}

Step 5 Connect or authenticate to Sendbird server

Copy link

There are two methods to connect to the Sendbird server: SendbirdUIKit.connect() and SendbirdUIKit.authenticate().

If you wish to only implement in-app channels for Business Messaging in your client app, it's highly recommended that you authenticate a user to the Sendbird server. If you're already using Chat SDK and want to additionally implement Business Messaging in-app channels, then you should connect a user to the Sendbird server.

Connect a user

Copy link

Connect a user to the Sendbird server using the SendbirdUIKit.connect() method with the information you provided in SendbirdUIKitAdapter. The connect() method also automatically updates the user profile on the server. You need to call this method to connect to the Sendbird server. The SendbirdUIKit.connect() method creates an active WebSocket connection with the server, which allows the Chat SDK to receive real-time events.

With local caching added to Sendbird Chat SDK, the latest user instance may be returned through the callback even when the user is offline. The local caching functionality stores message and channel data in the local storage and Sendbird server. As a result, even when a user is not connected to the server, the user information stored in the local cache is returned through the callback along with an error indicating the offline status.

Refer to the code below to see how to connect a user to the Sendbird server:

JavaKotlin
SendbirdUIKit.connect(new ConnectHandler() {
   @Override
   public void onConnected(User user, SendbirdException e) {
       if (user != null) {
           if (e != null) {
               // Proceed in offline mode with the data stored in the local database.
               // Then when a connection is made automatically,
               // you can be notified through ConnectionHandler.onReconnectSucceeded().
           } else {
               // Proceed in online mode.
           }
       } else {
           // Handle error.
       }
   }
});

Note: Chat UIKit for Business Messaging automatically establishes a connection when necessary. If a connection with the Sendbird server is required before using a UIKit component, call SendbirdUIKit.connect().

Authenticate a user

Copy link

You can authenticate the user to Sendbird server using the SendbirdUIKit.authenticate() method with the information you provided in SendbirdUIKitAdapter. It's highly recommended to use this method to authenticate to the server if you're only displaying the in-app notification channel view in the client app.

When keeping your notification channels up to date, you can either create an active WebSocket connection with the server or manually refresh the channel with latest information. In this case where you're displaying a in-app notification channel view by authenticating a user to the server, you need to refresh notification collections to update your channel. This is because the Chat SDK can't receive real-time events to notify the user with updated information about the channel view when there's no active WebSocket connection with the server.

In order to use the SendbirdUIKit.authenticate() method, you must first issue a session token. After authenticating with the session token, you must set a session handler so that the client app can renew the token upon the user's session expiration. When using SendbirdUIKit.authenticate(), all session keys are set to expire so it's important that you implement the session handler in order to keep using Sendbird Business Messaging.

Then, you can call SendbirdUIKit.authenticate() to create a new user account or log in with an existing account with the specified user ID and session token. This method authenticates the UIKit and allows it to retrieve feed channels, display notification messages, and more. Refer to the code snippet below.

JavaKotlin
SendbirdUIKit.authenticate(new AuthenticationHandler() {
    @Override
    public void onAuthenticated(@Nullable User user, @Nullable SendbirdException e) {
        if (user != null) {
            if (e != null) {
                // Proceed in offline mode with the data stored in the local database.
            } else {
                // Proceed in online mode.
            }
        } else {
            // Handle error.
        }
    }
});

Note: If you use the authenticate() method to connect to the Sendbird server, you can't access group channels or open channels. Error messages, such as User auth session is not allowed to use requested service.`, will be returned when trying to use Chat SDK's public interfaces.

Step 6 Add BaseApplication

Copy link

Add the created BaseApplication to AndroidManifest.xml.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.sendbird.uikitapplication">

    <!--  sets android:name  -->
    <application

        android:name=".BaseApplication"

        >
    </application>
</manifest>

Step 7 Register push notification credentials

Copy link

In order to receive push notifications, you need to register notification credentials first. You can set up push notifications for either FCM or HMS. For FCM, register your server key and a registration token. For HMS, register your app ID and app secret.

You can also implement push notifications with multi-device support if you want to send a push notification even when the client app is in the foreground. Refer to the multi-device support guide for FCM or HMS.

Step 8 Display notification channel

Copy link

Refer to the codes below to display either in-app channel view or channel list view where you can see the notifications that were sent to the channel.

Feed view

Copy link

In order to display the in-app notification channel view, you need to first find its channel URL on Sendbird Dashboard under Business Messaging > Channels.

Start an activity by using intent to move from one activity to FeedNotificationChannelActivity.

JavaKotlin
Intent intent = FeedNotificationChannelActivity.newIntent(context, "FEED_CHANNEL_CHANNEL_URL");
startActivity(intent);

FeedNotificationChannelActivity allows you to create a basic FeedNotificationChannelFragment through UIKitFragmentFactory and FeedNotificationChannelFragment.Builder. UIKitFragmentFactory has a set of methods that build each fragment, whereas the builder class provides APIs to customize the UI of the data and event handlers used in FeedNotificationChannelFragment.

JavaKotlin
FeedNotificationChannelFragment fragment = new FeedNotificationChannelFragment.Builder("FEED_CHANNEL_CHANNEL_URL").build();