How to Integrate Chat Features into Client Apps Via Sendbird's API

VoIP calls, real-time chat and messaging have become ubiquitous in business for one reason: They work.

Consumers have come to expect the ability to instantly contact service providers. This kind of communication can drive sales and lead to greater customer satisfaction. The downside is that developing this kind of functionality in-house is often resource intensive. Additionally, it may not make sense for a lot of companies amid the COVID-19 pandemic and a slumping economy. Turning to an API for functionality that you might otherwise have developed in house can save on development costs while speeding the feature's time to market.

In this article, we provide instructions on how to quickly implement the Sendbird UIKit for iOS and deploy fully-featured messaging using pre-built UI and messaging UX. Sendbird UIKit for iOS is essentially a combination of user interface tooling and the Sendbird Chat SDK for iOS.

Getting started

Some things to keep in mind. Sendbird UIKit for iOS is a development kit with a user interface that enables the integration of standard chat features into new or existing client apps.

From the overall theme to individual styles, such as colors and fonts, components can be fully customized for a company's brand identity.

Currently, UIKit for iOS supports group channels only, that is channels with multiple people in them. The minimum requirements are iOS 10.3+, Swift 4.2+ / Objective-C and Sendbird Chat SDK for iOS 3.0.175+. For those wishing to test drive Sendbird's sample app, they can access it from our GitHub repository.

Sendbird UIKit supports both Objective-C and Swift, so users can create a project in the language they want to develop with.

Choose options for your new project

UIKit for iOS can be installed through either CocoaPods or Carthage:

For CocoaPods

  1. Add SendBirdUIKit into your Podfile in Xcode as below:

            platform :ios, '10.3' 
            use_frameworks! 
    
            target YOUR_PROJECT_TARGET do
                pod 'SendBirdUIKit'
            end
  2. Install the SendBirdUIKit framework through CocoaPods.
    $ pod install
  3. Update the SendBirdUIKit framework through CocoaPods.
    $ pod update

Note: The Sendbird UIKit for iOS is Sendbird Chat SDK-dependent. If you install the UIKit, CocoaPods will automatically install the Chat SDK for iOS as well. The minimum requirement of the Chat SDK for iOS is 3.0.175 or higher.

For Carthage

  1. Add SendBirdUIKit into your Cartfile as below:

    github "sendbird/sendbird-uikit-ios"
  2. Install the SendBirdUIKit framework through Carthage.
    $ cartage update 
  3. Go to your Xcode project target's General settings tab in the Frameworks and Libraries section. Then drag and drop on the disk each framework from the <YOUR_XCODE_PROJECT_DIRECTORY>/Carthage/Build/iOS folder.
  4. Go to your Xcode project target's Build Phases settings tab, click the + icon, and choose New Run Script Phase. Create a Run Script, specify your shell (ex: /bin/sh), and add /usr/local/bin/carthage copy-frameworks to the script below the shell.

Media attachment permission

Sendbird UIKit offers features to attach or save files such as photos, videos, and documents. To use those features, you need to request permission from end users.Once the permission is granted, users can send image or video messages and save media assets.

Next, place the below code in the Info.plist file present in the root folder of your iOS project. This will help in creating in application notifications to request for permissions.

...
<key>NSPhotoLibraryUsageDescription</key>
    <string>$(PRODUCT_NAME) would like access to your photo library</string>
<key>NSCameraUsageDescription</key>
    <string>$(PRODUCT_NAME) would like to use your camera</string>
<key>NSMicrophoneUsageDescription</key>
    <string>$(PRODUCT_NAME) would like to use your microphone (for videos)</string>
<key>NSPhotoLibraryAddUsageDescription</key>
    <string>$(PRODUCT_NAME) would like to save photos to your photo library</string>
...
Media attachment permission

(Optional) Document attachment permission
If you want to attach files from iCloud, you must activate the iCloud feature. Once it is activated, users can also send a message with files from iCloud.

Go to your Xcode project's Signing & Capabilities tab. Then, click + Capability button and select iCloud. Check iCloud Documents.

(Optional) Document attachment permission

Implementation guide

Initialize with an APP_ID

In order to use the Chat SDK's features, you must initialize the SendBirdUIKit instance with an APP_ID. This step also initializes the Chat SDK for iOS. Initialize the SendBirdUIKit instance through AppDelegate as shown by putting the code in the AppDelegate.m file:

// AppDelegate.m

@import SendBirdUIKit;
...

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    ...
    NSString *APP_ID = @"2D7B4CDB-932F-4082-9B09-A1153792DC8D"; // The ID of the Sendbird application which UIKit sample app uses..
    [SBUMain initializeWithApplicationId:APP_ID];
    ...

Note : In the above, you should specify the ID of your Sendbird application in place of the APP_ID.

Set the current user

User information must be set as CurrentUser in the SBUGlobal prior to launching the Sendbird UIKit. This information will be used within the kit for various tasks. The userId field must be specified whereas other fields such as nickname and profileUrl are optional and filled with default values if not specified.

Set the CurrentUser for UIKit through the AppDelegate.m file as below:

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

// AppDelegate.m
@import SendBirdUIKit;
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    ...
        // Case 1: USER_ID only
    [SBUGlobals setCurrentUser:[[SBUUser alloc] initWithUserId:{USER_ID} nickname:nil profileUrl:nil]];
    
    // Case 2: Specify all fields
    [SBUGlobals setCurrentUser:[[SBUUser alloc] initWithUserId:{USER_ID} nickname:{(opt)NICKNAME} profileUrl:{(opt)PROFILE_URL}]];
    ...
}

Note: If the CurrentUser is not set in advance, there will be restrictions to your usage of the UIKit.

Channel list

UIKit allows you to create a channel specifically for 1-on-1 chat and to list 1-on-1 chat channels so that you can easily view and manage them. With the SBUChannelListViewController class, you can provide end-users with a complete chat service featuring a channel list.

Use the following code for the SceneDelegate and AppDelegate by putting it in the SceneDelegate.m and AppDelegate.m files respectively

Objective-C

// SceneDelegate.m
@import SendBirdUIKit;
...
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
 ...
SBUChannelListViewController *channelListVC = [[SBUChannelListViewController alloc] init];
UINavigationController *naviVC = [[UINavigationController alloc] initWithRootViewController:channelListVC]; self.window.rootViewController = naviVC;}

Objective-C

// AppDelegate.m
@import SendBirdUIKit;
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    ...
SBUChannelListViewController *channelListVC = [[SBUChannelListViewController alloc] init];
 UINavigationController *naviVC = [[UINavigationController alloc] initWithRootViewController:channelListVC];
self.window.rootViewController = naviVC;}

Note: At this point, you can confirm if the service is working by running your client app.

Channel

With the SBUChannelViewController class, you can build a channel-based chat service instead of a channel list-based one. This code is used to open a chat between users. For example, if the user selects a chat icon in your application to chat with another user, you can use the below code to present the chat. This eliminates the need to show a channel list in the app if the app developer does not want to show a list.

Note: You should have either a SBDChannel object or a ChannelUrl in order to run a channel-based chat service. You can implement the code in AppDelegate.m or anywhere in your service where you'd like to implement chat in the manner stated above. Use the following code to implement the chat service:

Objective-C

@import SendBirdUIKit;
...
SBUChannelViewController *channelVC = [[SBUChannelViewController alloc] initWithChannelUrl:{CHANNEL_URL}];
UINavigationController *naviVC = [[UINavigationController alloc] initWithRootViewController:channelVC];
[self presentViewController:naviVC animated:YES completion:nil];

For Objective-C

UIKit is a Swift-based framework. However, If your project is in Objective-C, configuring just a few additional steps allows you to run the kit in your client app. Go to your Xcode project target's Build settings tab and then set the ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES to YES.

Distribution setting

UIKit is distributed in the form of a fat binary, which contains information on both Simulator and Device architectures. Add the script below if you are planning to distribute your application in the App Store and wish to remove unnecessary architectures in the application's build phase.

Go to your Xcode project target's Build Phases tab. Then, click + and select New Run Script Phase. Append this script.

APP_PATH="${TARGET_BUILD_DIR}/${WRAPPER_NAME}"
# This script loops through the frameworks embedded in the application and
# removes unused architectures.
find "$APP_PATH" -name '*.framework' -type d | while read -r FRAMEWORK
do
    FRAMEWORK_EXECUTABLE_NAME=$(defaults read "$FRAMEWORK/Info.plist" CFBundleExecutable)
    FRAMEWORK_EXECUTABLE_PATH="$FRAMEWORK/$FRAMEWORK_EXECUTABLE_NAME"
    echo "Executable is $FRAMEWORK_EXECUTABLE_PATH"

    EXTRACTED_ARCHS=()

    for ARCH in $ARCHS
    do
        echo "Extracting $ARCH from $FRAMEWORK_EXECUTABLE_NAME"
        lipo -extract "$ARCH" "$FRAMEWORK_EXECUTABLE_PATH" -o "$FRAMEWORK_EXECUTABLE_PATH-$ARCH"
        EXTRACTED_ARCHS+=("$FRAMEWORK_EXECUTABLE_PATH-$ARCH")
    done

    echo "Merging extracted architectures: ${ARCHS}"
    lipo -o "$FRAMEWORK_EXECUTABLE_PATH-merged" -create "${EXTRACTED_ARCHS[@]}"
    rm "${EXTRACTED_ARCHS[@]}"

    echo "Replacing original executable with thinned version"
    rm "$FRAMEWORK_EXECUTABLE_PATH"
    mv "$FRAMEWORK_EXECUTABLE_PATH-merged" "$FRAMEWORK_EXECUTABLE_PATH"
done

UIKit at a glance

The UIKit for iOS manages the lifecycle of its ViewController along with various views and data from the Chat SDK for iOS. UIKit Components are as follows:

UIKit at a glance

Authentication

In order to use the features of Sendbird UIKit for iOS in your client apps, a SendBirdUIKit instance must be initiated in each client app through user authentication with the Sendbird server.

The instance communicates and interacts with the server using an authenticated user account, and is allowed to use the UIKit's features. This page explains how to authenticate your user with the server.

Set an access token

Sendbird server authenticates requests from client apps through two methods: One is using only user ID, the other is using a user ID along with the user's access token.

The user ID authentication can be useful for applications in development or existing services where additional security is not necessarily needed. On the other hand, the access token authentication generates access tokens for each user through the Chat Platform API.

Once you request and obtain a token for a user, you need to use that specific access token to authenticate the user. This goes in the AppDelegate.m file.

Objective-C

[SBUGlobals setAccessToken:{ACCESS_TOKEN}];

Connect to the Sendbird server

The SBUMain.connect() method connects a user to the Sendbird server using the preset information of the CurrentUser. If the user ID used during the connection attempt does not exist on the Sendbird server, a new user account is created with the specified user ID.

The SBUMain.connect() method also automatically updates the user profile on the Sendbird server.

When the ViewController is called in the UIKit, the connection is automatically made with the CurrentUser information which was set in the SBUGlobal.

In case you want to connect to the Sendbird server at a particular timing, you can use the code as below. This goes in the AppDelegate.m file:

[SBUMain connectWithCompletionHandler:^(SBDUser * _Nullable user, SBDError * _Nullable error) {
    ...        
}];

Disconnect from the Sendbird server

When a user doesn't need to receive messages from the Sendbird server, it is recommended to disconnect the user from the server. Even after disconnected, the user can still receive push notifications for new messages delivered by APNs (Apple Push Notification Service). To implement this, please put this code in the AppDelegate.m file:

[SBUMain disconnectWithCompletionHandler:^{}];

Register for push notifications

Push notifications are a type of notification sent to your users' devices when an application is running in the background.

Push notifications for iOS applications will contain a payload created by Sendbird and be delivered through APNs. The Sendbird server will communicate with APNs whenever needed and APNs will send a push notification to the application on iOS devices.

In order to use this feature, you need to register the device tokens of your client app users to Sendbird server through the AppDelegate.m file.

Note: APNs should be set up in advance in order to send push notifications.

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    ...
  [SBUMain registerPushWithDeviceToken:deviceToken completionHandler:^(BOOL success) {
    }];
}

Note: You can use these methods when the SBUGlobal.CurrentUser is set and connected to the Sendbird server.

Unregister for push notifications

You should unregister a user's device tokens from the Sendbird server if you don't want to send push notifications to the user. This should only be used when you don't want to receive push notifications anymore. To implement this, please use the below code in the AppDelegate.m file:

// If you want to unregister the current device only, call this method.
[SBUMain unregisterPushTokenWithcompletionHandler:^(BOOL success) {
}];
// If you want to unregister all devices of the user, call this method.
[SBUMain unregisterAllPushTokenWithcompletionHandler:^(BOOL success) {
}];

Note: You can use these methods when the SBUGlobal.CurrentUser is set and connected to the Sendbird server.

Update user profile

When a CurrentUser is created with a unique ID of the user, the UIKit automatically generates the nickname and profileImage of the user based on the specified userId. You can also modify these properties by yourself when needed in the AppDelegate.m file.

Note: You can use this method when the SBUGlobal.CurrentUser is set and connected to the Sendbird server.

[SBUMain updateUserInfoWithNickname:{NICKNAME} profileUrl:{PROFILE_URL} completionHandler:^(SBDError * _Nullable) { 
    ...
}];

Now that you've achieved a bit of success with the Sendbird API, you can think about the variety of use cases it might be useful to. For example, converstaional ecommerce applications to help reduce buyer uncertainty, in-app chat during live streaming events to increase audience engagement, or allowing an online money transfer through a chat interface instead of requiring a bank customer to go to a branch.

Be sure to read the next Application Development article: How to Secure Your Rails API Without Being a Security Expert

 

Comments (0)