Establish a connection
The application client must establish a successful connection to the Nexconn server before it can send and receive messages using the Nexconn Chat SDK.
When the Nexconn server receives a connection request from the client, it validates the user identity by checking the access token included in the request.
Prerequisites
- Register the user via the Server API Register User (Get Access Token). The client Chat SDK does not provide a method to obtain an access token. Your application client should call your own server, which in turn fetches the access token from the Nexconn server.
- After obtaining an access token, the client can store it for subsequent connections. The storage location depends on your client application design. If the access token has not expired, you do not need to request a new one.
- Access token expiry can be configured in the console. The default is no expiration. Even after a new access token is generated, unexpired old tokens remain valid. Once an access token expires, obtain a new one. If needed, you can proactively invalidate an access token via the Server API Invalidate Access Token.
- It is recommended to set up a connection status listener before connecting.
- The SDK must be initialized.
Do not call the server API to obtain an access token directly from the client. Obtaining an access token requires the App Key and App Secret. If these credentials are stored on the client and the application is decompiled, they will be exposed. Always obtain the access token from your application server.
Connect to the Chat server
Choose an appropriate time to connect to the Nexconn chat server based on your application's business needs (for example, on login, registration, or another suitable event to ensure the user can enter the main screen).
- You must call
connectafter the SDK is initialized. Otherwise, the callback may not fire. - The SDK implements an internal reconnection mechanism. When a network issue causes the IM connection to drop, the SDK automatically reconnects until the application explicitly disconnects (see Disconnect).
Nexconn Chat SDK connection API
Method signature
- Swift
- Objective-C
static func connect(
params: ConnectParams,
databaseOpenedHandler: ((_ isRecreated: Bool, _ error: NCError?) -> Void)?,
completionHandler: ((_ userId: String?, _ error: NCError?) -> Void)?
)
+ (void)connectWithParams:(NCConnectParams *)params
databaseOpenedHandler:(nullable void (^)(BOOL isRecreated, NCError * _Nullable error))databaseOpenedHandler
completionHandler:(nullable void (^)(NSString * _Nullable userId, NCError * _Nullable error))completionHandler
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| params | NCConnectParams * | Yes | Connection parameters. token is required. |
| databaseOpenedHandler | Block | No | Database ready callback. error == nil means the local database is available; isRecreated == YES means the database was recreated and local data was cleared. |
| completionHandler | Block | No | Completion callback. On success: userId is the current user ID and error is nil. On failure: userId is nil and error contains the error details. |
NCConnectParams properties:
| Property | Type | Default | Description |
|---|---|---|---|
token | NSString * | — | User access token (required) |
timeout | int32_t | 0 | Connection timeout in seconds. ≤ 0: no limit, keeps reconnecting indefinitely. > 0: stops reconnecting after the specified seconds. |
reconnectKickEnable | BOOL | NO | Whether to kick the reconnecting device during reconnection. |
Usage notes
Common scenarios:
- Establishing an IM connection after user login.
- Reconnecting after network recovery.
- Reconnecting when the app returns to the foreground.
Important notes:
- Call
NCEngine.initialize(_:)before connecting. - When
timeout ≤ 0, the SDK keeps reconnecting indefinitely — suitable for always-online scenarios. - When
timeout > 0, the SDK stops reconnecting after the timeout — suitable for time-limited scenarios. - All callbacks are dispatched on the configured callback queue (default: main queue).
- Messages cannot be sent until the connection succeeds.
Example
- Swift
- Objective-C
import NexconnChatSDK
let params = ConnectParams(token: "access token retrieved from server")
params.timeout = 30
NCEngine.connect(
params: params,
databaseOpenedHandler: { isRecreated, error in
guard error == nil else { return }
// Local database is ready — safe to navigate to the main screen
if isRecreated {
// Local data was cleared; reload from remote as needed
}
},
completionHandler: { userId, error in
if let error {
print("Connection failed: \(error.localizedDescription)")
} else {
print("Connected successfully, user ID: \(userId ?? "")")
}
}
)
NCConnectParams *params = [[NCConnectParams alloc] initWithToken:@"access token retrieved from server"];
params.timeout = 30;
[NCEngine connectWithParams:params
databaseOpenedHandler:^(BOOL isRecreated, NCError * _Nullable error) {
if (error == nil) {
// Local database is ready — safe to navigate to the main screen
if (isRecreated) {
// Local data was cleared; reload from remote as needed
}
}
}
completionHandler:^(NSString * _Nullable userId, NCError * _Nullable error) {
if (error) {
NSLog(@"Connection failed: %@", error.localizedDescription);
} else {
NSLog(@"Connected successfully, user ID: %@", userId);
}
}];
Related APIs
NCEngine.initialize(_:)— Initialize the SDK (prerequisite).NCEngine.disconnect(disablePush:)— Disconnect.NCEngine.addMessageHandler(identifier:handler:)— Register a message handler.NCEngine.addDatabaseStatusHandler(identifier:handler:)— See Database events for database upgrade lifecycle callbacks.
Connection status codes
The NCError.errorCode returned in connection callbacks, and the NCConnectionStatus enum used in Monitor Connection Status, are as follows:
- When
NCConnectionStatus.tokenIncorrectis received, request a new access token from your server and reconnect. Be careful to avoid infinite loops that could degrade the user experience. - The callback thread is determined by the SDK's internal dispatch queue. Switch to the main thread for any UI operations.
NCConnectionStatus Value | rawValue | Description | Recommended Action |
|---|---|---|---|
NCConnectionStatusUnknown | -1 | Unknown status. The SDK usually reconnects automatically. | — |
NCConnectionStatusConnected | 0 | Connected successfully. | — |
NCConnectionStatusNetworkUnavailable | 1 | Current device network is unavailable. | Wait for network recovery; the SDK will reconnect automatically. |
NCConnectionStatusKickedOfflineByOtherClient | 6 | The current user logged in on another device, and this device was kicked offline. | Navigate to the login screen and notify the user. |
NCConnectionStatusConnecting | 10 | Connecting. | — |
NCConnectionStatusUnconnected | 11 | Connection failed or not connected. | Notify the user based on the error code. |
NCConnectionStatusSignOut | 12 | Signed out. | — |
NCConnectionStatusSuspend | 13 | Connection temporarily suspended; the SDK will reconnect at an appropriate time. | — |
NCConnectionStatusTimeout | 14 | Auto-reconnect timed out (only occurs when a valid timeout is set). The SDK stops reconnecting after this. | Prompt the user to wait for network recovery and reconnect manually. |
NCConnectionStatusTokenIncorrect | 15 | Access token is invalid or expired. This may occur if the SDK and the app server use different App Keys, or if the console has configured a token expiry. | Request a new access token from the app server and reconnect with it. |
NCConnectionStatusDisconnException | 16 | Disconnected from the server; the account has been banned. | Navigate to the login screen and notify the user of the account anomaly. |
NCConnectionStatusProxyUnavailable | 17 | Proxy service is unavailable. | Check the proxy configuration and reconnect. |
NCConnectionStatusUserAbandon | 19 | The user account has been deleted. | Navigate to the login screen and notify the user that the account has been deactivated. |