Skip to main content

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.
tip

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).

tip
  • You must call connect after 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
static func connect(
params: ConnectParams,
databaseOpenedHandler: ((_ isRecreated: Bool, _ error: NCError?) -> Void)?,
completionHandler: ((_ userId: String?, _ error: NCError?) -> Void)?
)

Parameters

ParameterTypeRequiredDescription
paramsNCConnectParams *YesConnection parameters. token is required.
databaseOpenedHandlerBlockNoDatabase ready callback. error == nil means the local database is available; isRecreated == YES means the database was recreated and local data was cleared.
completionHandlerBlockNoCompletion 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:

PropertyTypeDefaultDescription
tokenNSString *User access token (required)
timeoutint32_t0Connection timeout in seconds. ≤ 0: no limit, keeps reconnecting indefinitely. > 0: stops reconnecting after the specified seconds.
reconnectKickEnableBOOLNOWhether to kick the reconnecting device during reconnection.

Usage notes

Common scenarios:

  1. Establishing an IM connection after user login.
  2. Reconnecting after network recovery.
  3. Reconnecting when the app returns to the foreground.

Important notes:

  1. Call NCEngine.initialize(_:) before connecting.
  2. When timeout ≤ 0, the SDK keeps reconnecting indefinitely — suitable for always-online scenarios.
  3. When timeout > 0, the SDK stops reconnecting after the timeout — suitable for time-limited scenarios.
  4. All callbacks are dispatched on the configured callback queue (default: main queue).
  5. Messages cannot be sent until the connection succeeds.

Example

swift
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 ?? "")")
}
}
)
  • 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:

tip
  1. When NCConnectionStatus.tokenIncorrect is received, request a new access token from your server and reconnect. Be careful to avoid infinite loops that could degrade the user experience.
  2. The callback thread is determined by the SDK's internal dispatch queue. Switch to the main thread for any UI operations.
NCConnectionStatus ValuerawValueDescriptionRecommended Action
NCConnectionStatusUnknown-1Unknown status. The SDK usually reconnects automatically.
NCConnectionStatusConnected0Connected successfully.
NCConnectionStatusNetworkUnavailable1Current device network is unavailable.Wait for network recovery; the SDK will reconnect automatically.
NCConnectionStatusKickedOfflineByOtherClient6The current user logged in on another device, and this device was kicked offline.Navigate to the login screen and notify the user.
NCConnectionStatusConnecting10Connecting.
NCConnectionStatusUnconnected11Connection failed or not connected.Notify the user based on the error code.
NCConnectionStatusSignOut12Signed out.
NCConnectionStatusSuspend13Connection temporarily suspended; the SDK will reconnect at an appropriate time.
NCConnectionStatusTimeout14Auto-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.
NCConnectionStatusTokenIncorrect15Access 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.
NCConnectionStatusDisconnException16Disconnected from the server; the account has been banned.Navigate to the login screen and notify the user of the account anomaly.
NCConnectionStatusProxyUnavailable17Proxy service is unavailable.Check the proxy configuration and reconnect.
NCConnectionStatusUserAbandon19The user account has been deleted.Navigate to the login screen and notify the user that the account has been deactivated.