Chat / iOS
Chat iOS v4
Chat iOS
Chat
iOS
Home
/
Chat
/
iOS
/
Application
This is the new Docs for Chat SDK v4 for iOS. To see the previous Docs, click here.

Authentication

In order to use the features of the Chat SDK for JavaScript in your client apps, a SendbirdChat instance should be initiated in each client app through user authentication with the Sendbird server. The instance communicates and interacts with the server based on the 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 the Chat SDK with APP_ID

To use our chat features, you must initialize the SendbirdChat instance by passing APP_ID of your Sendbird application as an argument to a parameter of the initialize(params:migrationStartHandler:completionHandler:) method. The initialize(params:migrationStartHandler:completionHandler:) method must be called once across your client app. Typically, initialization is implemented in the user login view.

// Initialize SendbirdChat instance to use APIs in your app.
let initParams = InitParams(applicationId: APP_ID)
SendbirdChat.initialize(params: initParams) {

} completionHandler: { error in
    guard error == nil else {
        // Handle error.
        return
    }
}

With the implementation of local caching, the isLocalCachingEnabled property of the InitParams object has been added. Additionally, two callback functions, migrationStartHandler and completionHandler, have also been added to the initialization code as shown below.

// Initialize a SendbirdChat instance to use APIs in the client app.
let initParams = InitParams(applicationId: APP_ID, isLocalCachingEnabled: true)

SendbirdChat.initialize(params: initParams) {

} completionHandler: { error in
    guard error == nil else {
        // Handle error.
        return
    }
}

The isLocalCachingEnabled parameter determines whether or not the client app will use local storage through Sendbird Chat SDK. Since this is optional, the default value is set to false. If you want to build a client app with our local caching functionalities, set the isLocalCachingEnabled parameter to true.

Then, the completionHandler gets the initialization status through different event handlers and informs the client app whether the initialization is successful or not. On the other hand, the migrationStartHandler is called when the migration for local caching has started.

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


Connect to the Sendbird server with a user ID

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

While authenticating with just the user ID is convenient in the developing and testing stages of a service, a more secure authentication process using tokens is strongly recommended for most production environments.

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

// The USER_ID argument below should be unique to your Sendbird application.
SendbirdChat.connect(userId: USER_ID) { user, error in
    guard error == nil else {
        // Handle error.
        return
    }

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

Note: Apart from initializing the SendbirdChat instance, you should connect to the Sendbird server before calling almost every method through the Chat SDK. If you attempt to call a method without connecting, a .connectionRequired (800101) error will be returned.


Connect to the Sendbird server with a user ID and a token

For a more secure way of authenticating a user, you can require an authentication token, which can be an access token or a session token, in addition to a unique user ID. Any token issued for a user must be provided to the Sendbird server each time the user logs in by passing the token as an argument to the authToken parameter of the connect(userId:authToken:completionHandler:) method.

Using an access token

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 connect() method which is used for logging in.

  1. Using the Chat API, create a Sendbird user account with information submitted when a user signs up or logs 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 connect(userId:authToken: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 on your dashboard, you're able to prevent users without an access token from logging in to your Sendbird application or restrict their access to read and write messages.

// The USER_ID argument below should be unique to your Sendbird application.
SendbirdChat.connect(userId: USER_ID, authToken: ACCESS_TOKEN) { user, error in
    guard error == nil else {
        // Handle error.
        return
    }

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

Using a session token

You can also use a session token instead of an access token to authenticate a user. Session tokens are a more secure option because they expire after a certain period whereas access tokens don't. See Chat Platform API guides for further explanation 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

When a user is authenticated with a session token, the Chat SDK connects the user to the Sendbird server and can send data requests to the server 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 SessionDelegate. 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 SessionDelegate instance to refresh the token and pass it back to the SDK so that it can refresh the session again.

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

The following code shows how to implement the delegate methods.

extension CustomObject: SessionDelegate {
    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 don't want to refresh the session, pass on a nil value through success(nil).
        // If any error occurs while refreshing the token, let the SDK know about it through fail().
    }

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

    func sessionWasRefreshed() {
        // Optional. No action is required.
        // This is called when the session is refreshed.
    }

    func sessionDidHaveError(_ error: SBError) {
        // Optional. No action is required.
        // This is called when an error occurs during the session refresh.
    }
}

Disconnect from the Sendbird server

A user can be disconnected from the 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 add(_: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 getChannel(url:completionHandler:) method of OpenChannel or GroupChannel is called, are also flushed.

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

SendbirdChat.disconnect {
    // The current user is disconnected from the Sendbird server.
}