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

Authentication

Copy link

In order to use the features of the Chat SDK in your client apps, a SBDMain instance must be initiated in each client app through user authentication with Sendbird server. The instance communicates and interacts with the server using an authenticated user account, and is allowed to use the Chat SDK's features. This page explains how to authenticate your user with the server.


Initialize with APP_ID

Copy link

To use our chat features, you must initialize a SBDMain instance by passing the APP_ID of your Sendbird application as an argument to a parameter of the initWithApplicationId: method. The initWithApplicationId: must be called once across your client app. Generally, initialization is implemented in the user login view controller.

SwiftObjective-C
// The USER_ID below should be unique to your Sendbird application.
SBDMain.connect(withUserId: USER_ID, completionHandler: { (user, error) in
    guard error == nil else {
        // Handle error.
    }

    // The user is connected to Sendbird server.
    ...
})

Note: The code above will be deprecated soon. Use the new code with or without local caching instead.

With local caching, two new parameters have been added to the initialization code, which are useCaching and completionHandler.

The useCaching determines whether the client app will use the local storage through Sendbird Chat SDK or not. If you want to build a client app with our local caching functionalities, set the useCaching to true.

The completionHandler: gets the initialization status through different event handlers. For Objective-C, the migrationStartHandler: is called when there's a change in the local cache. Meanwhile, the completionHandler: informs the client app whether the initialization is successful or not.

If the initialization fails when you set the useCaching to true, the SDK will operate normally and change the value of the useCaching to false. If you still wish to use the local caching, clear the database using the clearCachedDataWithCompletionHandler: and try the initialization again with the useCaching set to true.

SwiftObjective-C
// Initialize a SBDMain instance to use APIs in the client app.
SBDMain.initWithApplicationId(APP_ID, useCaching: false) {

} completionHandler: { error in

}

Connect to Sendbird server with a user ID

Copy link

By default, Sendbird server can authenticate a user just by a unique user ID. Then the server queries the database to check for a match upon the request for connection. If no matching user ID is found, the server creates a new user account with the user ID. The ID must be unique within a Sendbird application to be distinguished from others, such as a hashed email address or phone number in your service.

This authentication procedure is useful when in development or if your service doesn't require additional security.

Note: Go to the Event delegate page to learn more about the usages of the Chat SDK's delegates and callbacks.

SwiftObjective-C
// The USER_ID below should be unique to your Sendbird application.
SBDMain.connect(withUserId: USER_ID, completionHandler: { (user, error) in
    guard error == nil else {
        // Handle error.
    }

    // The user is connected to Sendbird server.
    ...
})

Note: You must connect to Sendbird server before calling any methods through the Chat SDK (apart from initializing a SBDMain instance). If you attempt to call a method without connecting, a SBDErrorConnectionRequired (800101) error would be returned.


Connect to Sendbird server with a user ID and a token

Copy link

When a user logs in to a client app using the Chat SDK, you can choose how to authenticate a user. A user authentication can be done with just their own user ID, but also with either an access token or a session token. If any token is issued for a user, it must be provided to Sendbird server each time the user logs in by using the SBDMain.connect() method.

Using an access token

Copy link

Through our Chat Platform API, an access token can be generated when creating a user. You can also issue an access token for an existing user. Once an access token is issued, a user is required to provide the access token in the SBDMain.connect() method which is used for logging in.

  1. Using the Chat API, create a Sendbird user account with the information submitted when a user signs up or in to your service.
  2. Save the user ID along with the issued access token to your persistent storage which is securely managed.
  3. When the user attempts to log in to a client app, load the user ID and access token from the storage, and then pass them to the connectWithUserId:accessToken:completionHandler: method.
  4. Periodically replacing the user's access token is recommended to protect the account.

Note: From Settings > Application > Security > Access token permission setting in your dashboard, you are able to prevent users without an access token from logging in to your Sendbird application or restrict their access to read and write messages.

SwiftObjective-C
// The USER_ID below should be unique to your Sendbird application.
SBDMain.connect(withUserId: USER_ID, accessToken: ACCESS_TOKEN, completionHandler: { (user, error) in
    guard error == nil else {
        // Handle error.
    }

    // The user is authenticated using the access token and is connected to Sendbird server.
    ...
})

Using a session token

Copy link

You can also use a session token instead of an access token to authenticate a user. It's a more secure option because session tokens expire after a certain period whereas access tokens don't. Our Chat Platform API guide further explains about the difference between access token and session token, how to issue a session token, and how to revoke all session tokens.


Set a session delegate

Copy link

When a user logs in to a client app using the Chat SDK, a user can be authenticated with a session token. If a user is authenticated with a session token, the Chat SDK connects the user to the Sendbird server and can send data requests to it for ten minutes as long as the session token hasn't expired or hasn't been revoked.

Upon the user's session expiration, the Chat SDK will refresh the session internally using a SBDSessionDelegate. However, if the session token has expired or has been revoked, the Chat SDK can't do so. In that case, the client app needs to implement a SBDSessionDelegate instance to refresh the token and pass it back to the SDK so that it can refresh the session again.

Note: A SBDSessionDelegate instance must be set before the server connection is requested.

The following code shows how to implement the delegate methods.

SwiftObjective-C
extension CustomObject: SBDSessionDelegate {
    func sessionTokenDidRequire(successCompletion success: @escaping (String?) -> Void, failCompletion fail: @escaping () -> Void) {
        // A new session token is required in the SDK to refresh the session.
        // Refresh the session token and pass it onto the SDK through `success(NEW_TOKEN)`.
        // If you do not want to refresh the session, pass on a nil value through `success(nil)`.
        // If any error occurred while refreshing the token, let the SDK know about it through `fail()`.
    }

    func sessionWasClosed() {
        // The session refresh has been denied from the app.
        // Client app should guide the user to a login page to log in again.
    }

    func sessionWasRefreshed() {
        // OPTIONAL. No action is required.
        // Called when the session is refreshed.
    }

    func sessionDidHaveError(_ error: SBDError) {
        // OPTIONAL. No action is required.
        // Called when an error occurred during the session refresh.
    }
}

// SBDMain.connect should be called after setting SBDSessionDelegate.

Disconnect from Sendbird server

Copy link

A user should be disconnected from Sendbird server when they no longer need to receive messages from an online state. However, the user will still receive push notifications for new messages from group channels they've joined.

When disconnected, all event delegates in a user's client app registered by the addChannelDelegate:identifier: or addConnectionDelegate:identifier: stop receiving event callbacks from the server. Then, all internally cached data in the client app, such as the channels that are cached when the getChannelWithUrl:completionHandler: method of the SBDOpenChannel or SBDGroupChannel is called, are also flushed.

Note: By default, most of the data related to users, channels, and messages are internally cached in the SBDMain instance of a user's client app, which are retrieved by the corresponding query instances or received through the event delegates.

SwiftObjective-C
SBDMain.disconnect(completionHandler: {
    // The current user is disconnected from Sendbird server.

})

Update user profile

Copy link

Using the updateCurrentUserInfoWithNickName: method, you can update a user's nickname and profile image with a URL.

SwiftObjective-C
SBDMain.updateCurrentUserInfo(withNickname: NICKNAME, profileUrl: PROFILE_URL, completionHandler: { (error) in
    guard error == nil else {
        // Handle error.
    }

    // The current user's profile is successfully updated.
    // You could redraw the profile in a view in response to this operation.
    ...
})

Or, you can directly upload a profile image like the following:

SwiftObjective-C
SBDMain.updateCurrentUserInfo(withNickname: NICKNAME, profileImage: PROFILE_FILE, completionHandler: { (error) in
    guard error == nil else {
        // Handle error.
    }

    // A new profile images is successfully uploaded to Sendbird server.
    // You could redraw the profile in a view in response to this operation.
    ...
})

Note: A user's profile image can be a JPG (.jpg), JPEG (.jpeg), or PNG (.png) file of up to 5 MB.