Skip to main content

Establish a connection

Before using Chat UI SDK's messaging features, your client application must establish a successful connection to the instant messaging service.

When receiving a connection request, the server verifies the user's access token (Token parameter) to determine whether to allow the connection.

Prerequisites

  • Obtain an access token through the server API User Registration (Get Token). The client SDK doesn't provide token retrieval methods. Your application should call its own server to obtain tokens.
    • After obtaining the token, clients may store it for future connections. The storage location depends on your application design. If the token remains valid, there's no need to request a new one.
    • Token validity periods are configurable in the console. Expired tokens require renewal. You may actively invalidate tokens using the server API Expire Token.
  • We recommend setting up connection status monitoring before establishing a connection.
  • Complete SDK initialization first.
tip

Never call server APIs directly from the client to obtain tokens. Token retrieval requires sensitive application credentials. Storing these credentials in client code risks exposure if the app is decompiled. Always obtain tokens through your application server.

Connect to Chat Server

Initiate the connection at an appropriate moment (login, registration, or other events) based on your application's business requirements and design.

Important notes:

  • You must call connectWithParams after SDK initialization. Calling it earlier may prevent callbacks.
  • The SDK implements automatic reconnection. When network issues cause disconnections, it will retry until the app actively disconnects (see Disconnect).

Connection with timeout

For first-time connections, we recommend setting a connection timeout (timeout) in seconds. This allows handling timeout scenarios through error callbacks, where you can notify users (e.g., suggest retrying when network conditions improve).

Once connected successfully, the SDK's reconnection mechanism takes over. It will automatically retry during network outages until successful. Manual reconnection isn't needed unless the app actively disconnects (see Disconnect). For other scenarios, see Reconnection Mechanism and Multi-Device Conflict.

For password-free login, set timeout to 0 and perform page navigation in the databaseOpenedHandler callback to display local history data first, while letting the SDK handle connection logic.

Interface prototype

Objective C
- (void)connectWithParams:(NCConnectParams *)params
databaseOpenedHandler:(nullable void (^)(BOOL isRecreated, NCError * _Nullable error))databaseOpenedHandler
completionHandler:(nullable void (^)(NSString * _Nullable userId, NCError * _Nullable error))completionHandler;

Parameters

ParameterTypeRequiredDescription
tokenNSString *YesMust be obtained from your app server for initial connections. See server API docs User Registration.
timeoutint32_tNoConnection timeout in seconds. When timeout <= 0, the SDK keeps retrying until success or unrecoverable errors occur.
reconnectKickEnableBOOLNoWhether to kick other devices when reconnecting successfully. Defaults to NO. See Reconnection Mechanism and Multi-Device Conflict.
databaseOpenedHandlerBlock-Callback when local message database opens.
completionHandlerBlock-Connection completion callback. Returns user ID on success or NCError on failure.

Example code

Objective C
NCConnectParams *params = [[NCConnectParams alloc] initWithToken:@"Token value obtained by developer's server through server API"];
params.timeout = 30;

[[NCChatUI shared] connectWithParams:params
databaseOpenedHandler:^(BOOL isRecreated, NCError * _Nullable error) {
// Message database opened, proceed to main interface
} completionHandler:^(NSString * _Nullable userId, NCError * _Nullable error) {
if (userId.length > 0 && error == nil) {
// Connection succeeded
} else if (error.code == 15) {
// Token error - verify App Key consistency between SDK initialization and token retrieval
} else if (error.code == 14) {
// Connection timeout - notify user to retry when network improves
} else {
// Connection failed - handle according to error code
}
}];

Connection without timeout

Use this method when users have previously connected successfully and have local message history.

Since historical data exists, immediate connection isn't critical. Navigate to the main interface in databaseOpenedHandler to display local data first, while letting the SDK handle connection automatically.

tip

Callbacks may be delayed significantly under poor network conditions.

After calling this method, the SDK's reconnection mechanism takes over completely. It will retry until successful without manual intervention. Active disconnection stops this mechanism (see Disconnect). For other scenarios, see Reconnection Mechanism and Multi-Device Conflict.

Example code

Objective C
NCConnectParams *params = [[NCConnectParams alloc] initWithToken:@"Token value obtained by developer's server through server API"];

[[NCChatUI shared] connectWithParams:params
databaseOpenedHandler:^(BOOL isRecreated, NCError * _Nullable error) {
// Message database opened, proceed to main interface
} completionHandler:^(NSString * _Nullable userId, NCError * _Nullable error) {
if (userId.length > 0 && error == nil) {
// Connection succeeded
} else {
// Connection failed - handle according to error code
}
}];

Connection status codes

Refer to NCError code descriptions for detailed explanations and handling suggestions.

tip

Token-related error notes:

  1. For invalid tokens, request a new token from your server and reconnect—but avoid infinite loops that degrade user experience.
  2. Callbacks don't execute on the original calling thread. Switch to main thread for UI operations.
Error codeValueDescriptionRecommended action
Token incorrect15Invalid or incorrect token. Often occurs when client SDK and app server use different App Keys.Verify App Key consistency and obtain new token if needed.
Connect timeout14Reconnection timeout. Occurs in no-network environments only when timeout is set. SDK stops retrying after timeout.Manually reconnect by calling the connection interface again.
Kicked offline by other client6Current user logged in from another device, kicking this one offline.Return to login screen with user notification.
Disconn exception16Server connection terminated due to user ban.Return to login screen with user notification.
Proxy unavailable17Proxy service unavailable.Check proxy configuration and reconnect.
User abandon19User account deactivated.Notify user of account status issue.