Skip to main content

Establish Connection

The application client must successfully connect to RC servers before using the messaging functionality of RC's IM SDK.

When receiving a connection request from the client, RC's server will determine whether to allow the connection based on the user authentication token (Token parameter) carried in the request.

Prerequisites

  • Obtain a Token through the server-side API [User Registration (Get Token)]. The RC client SDK does not provide methods for obtaining Tokens. Applications should call their own server to obtain Tokens from RC's servers.
    • After obtaining the Token, the client can optionally save it for subsequent connections. The specific storage location depends on the application client design. If the Token remains valid, there's no need to request a new one from RC.
    • Token validity periods can be configured in the Console, with permanent validity as the default setting. Even when generating a new Token, the old unexpired Token remains valid. When a Token expires, you need to obtain a new one. If needed, you can actively call the server API Invalidate Token.
  • It's recommended that applications set up connection status monitoring before connecting.
  • The SDK must be initialized.
tip

Do not call server APIs directly from the client to obtain Tokens. Obtaining a Token requires providing the App Key and App Secret. If these credentials are stored on the client and the app is decompiled, it could lead to leakage of the App Key and App Secret. Therefore, always ensure Tokens are obtained from your application server.

Connect to Chat Server

Determine the appropriate timing (login, registration, or other scenarios to prevent inability to access the app home page) to initiate a connection request to RC's chat server based on your application's business requirements and design.

tip
  • The connect method must be called after SDK initialization. Otherwise, callbacks may not be received.
  • The SDK implements an automatic reconnection mechanism. When the IM connection is interrupted due to network issues, it will automatically reconnect until the application actively disconnects (see Disconnect).

Interface (With Timeout Setting)

For first-time connections to the chat server, it's recommended to use the interface with a connection timeout parameter (timeLimit) and set the timeout duration in seconds. In cases of poor network conditions causing connection timeouts, you can utilize the timeout error callback to notify users through UI prompts, such as suggesting they retry when network conditions improve.

Once successfully connected, the SDK's reconnection mechanism immediately takes effect and handles all reconnection processes. When disconnection occurs due to network issues, the SDK will continuously attempt reconnection until successful, requiring no additional connection operations from you. Active disconnection by the application will exit the reconnection mechanism (see Disconnect). For other scenarios, refer to Reconnection Mechanism and Reconnection Kick.

For password-free login, setting the timeLimit parameter to 0 allows page navigation immediately after the database opening callback (dbOpenedBlock), prioritizing display of local historical data while fully delegating connection logic to the SDK.

Interface Prototype

- (void)connectWithToken:(NSString *)token
timeLimit:(int)timeLimit
dbOpened:(nullable void (^)(RCDBErrorCode code))dbOpenedBlock
success:(nullable void (^)(NSString *userId))successBlock
error:(nullable void (^)(RCConnectErrorCode errorCode))errorBlock;

Parameter Description

ParameterTypeDescription
tokenNSStringRequired for initial connection. Must be obtained by your app server calling RC server APIs. See server API documentation User Registration
timeLimitintSDK connection timeout duration in seconds
dbOpenedBlockBlockCallback for local message database opening
successBlockBlockCallback for successful connection establishment
errorBlockBlockCallback for failed connection establishment
  • timeLimit Parameter Details:

    ParameterValue RangeDescription
    timeLimit≤ 0The SDK will continue connecting until successful or encountering unrecoverable errors (e.g., invalid token), equivalent to the connection interface above.
    timeLimit> 0The SDK will attempt connection for up to timeLimit seconds. If timeout occurs, returns RC_CONNECT_TIMEOUT error and stops reconnecting.
  • dbOpenedBlock Details:

    Callback ParameterCallback TypeDescription
    codeRCDBErrorCodeWhether the database is opened
  • successBlock Details:

    Callback ParameterCallback TypeDescription
    userIdNSStringUser ID of the successfully connected user
  • errorBlock Details:

    Callback ParameterCallback TypeDescription
    statusRCConnectErrorCodeError code for connection failure. See Connection Status Codes below.

Example Code

[[RCCoreClient sharedCoreClient] connectWithToken:@"Token value obtained by developer's server through server API"
timeLimit:30
dbOpened:^(RCDBErrorCode code) {
//Message database opened, can proceed to main interface
} success:^(NSString *userId) {
//Connection successful
} error:^(RCConnectErrorCode errorCode) {
if (errorCode == RC_CONN_TOKEN_INCORRECT) {
//Token error, verify whether the App Key used for SDK initialization matches the one used by the app server to obtain the Token
} else if(errorCode == RC_CONNECT_TIMEOUT) {
//Connection timeout, show prompt suggesting users retry when network conditions improve
} else {
//Unable to connect to IM server, handle according to the specific error code
}
}]

Interface (Without Timeout Setting)

This interface is recommended when the client user has previously successfully logged into your application and connected to RC's chat server, and is now logging in offline.

Since the user already has historical data, there's no strict dependency on successful connection. You can navigate pages immediately after the database opening callback (dbOpenedBlock) to prioritize displaying local historical data, while fully delegating connection logic to the SDK.

tip

This interface has been available since SDK version 5.20.0.

After calling this interface, the SDK's reconnection mechanism immediately takes effect and handles all reconnection processes. The SDK will continuously attempt reconnection until successful, requiring no additional connection operations from you. Active disconnection by the application will exit the reconnection mechanism (see Disconnect). For other scenarios, refer to Reconnection Mechanism and Reconnection Kick.

Interface Prototype

- (void)connectWithToken:(NSString *)token
dbOpened:(nullable void (^)(RCDBErrorCode code))dbOpenedBlock
success:(nullable void (^)(NSString *userId))successBlock
error:(nullable void (^)(RCConnectErrorCode errorCode))errorBlock;

Parameter Description

ParameterTypeDescription
tokenNSStringRequires your Server to access RC services to obtain Token
dbOpenedBlockBlockCallback for local message database opening
successBlockBlockCallback for successful connection establishment
errorBlockBlockCallback for failed connection establishment
  • dbOpenedBlock description:

    Callback ParameterCallback TypeDescription
    codeRCDBErrorCodeWhether the database is opened
  • successBlock description:

    Callback ParameterCallback TypeDescription
    userIdNSStringUser ID of the successfully connected user
  • errorBlock description:

    Callback ParameterCallback TypeDescription
    statusRCConnectErrorCodeError code for connection failure. See Connection Status Codes below for details.

Sample Code

[[RCCoreClient sharedCoreClient] connectWithToken:@"Token value obtained by the developer's server through the server API request"
dbOpened:^(RCDBErrorCode code) {
//Message database opened, can proceed to the main interface
}
success:^(NSString *userId) {
//Connection successful
}
error:^(RCConnectErrorCode errorCode) {
if (errorCode == RC_CONN_TOKEN_INCORRECT) {
//Obtain a new token from the app server and reconnect
} else {
//Unable to connect to the IM server, handle accordingly based on the error code
}
}]

Connection Status Codes

Refer to the table below for specific RCConnectErrorCode error codes and recommended handling solutions.

tip

Notes about RC_CONN_TOKEN_INCORRECT:

  1. In case of RC_CONN_TOKEN_INCORRECT, you need to request your server to obtain a new Token and establish a connection, but avoid infinite loops to prevent affecting the user experience.
  2. The callback thread of this method is not the original calling thread. When performing UI operations, make sure to switch to the main thread.
Error CodeValueDescriptionHandling Solution
RC_CONN_TOKEN_INCORRECT31004Token error. Commonly occurs when the App Key used by the client SDK does not match the one used by the App server. Each RC application provides two independent sets of App Key / Secret for isolating production and development environments. Switching from a test environment to a production environment may easily cause inconsistencies between the client and server App Keys.Verify that the SDK and App server are using the same App Key.
RC_CONN_TOKEN_EXPIRE31020Token expired. Commonly occurs when a Token expiration time is set in the Console. After the Token expires, your App server needs to request a new Token from RC, and the client should reconnect with the new Token.The client should request the App server to obtain a new Token from RC. Upon receiving the new Token, the client should initiate a connection with it.
RC_DISCONN_KICK31010User was kicked offline after successful connectionReturn to the login page and notify the user that they were kicked offline.
RC_CONN_OTHER_DEVICE_LOGIN31023The user logged in on another device during the connection process, causing the current device to be kicked.Return to the login page and notify the user that the account was logged in on another device.
RC_CONN_USER_BLOCKED31009User connection was terminated due to being banned while online.Return to the login page and notify the user that the account was banned.
RC_CONNECT_TIMEOUT34006Auto-reconnection timeout. Commonly occurs in a no-network environment and only happens when the connection interface is called with a valid timeout setting. The SDK will abandon reconnection after timeout. Developers need to notify users and may prompt them to reconnect when the network is restored.Manually reconnect by calling the connection interface again.
RC_CONN_APP_BLOCKED_OR_DELETED31008AppKey was bannedCheck if the AppKey you are using has been banned or deleted.
RC_CONN_PROXY_UNAVAILABLE31028Proxy service unavailable
RC_CLIENT_NOT_INIT33001SDK not initializedBefore using any SDK functionality, initialization is required.
RC_INVALID_PARAMETER33003Invalid parameters passed during developer interface callVerify the parameter types and values passed during the interface call.
DATABASE_ERROR33002Database errorCheck if the userId contains special characters. The SDK userId supports a combination of uppercase/lowercase letters, numbers, and some special symbols + = - _, with a maximum length of 64 bytes.