Skip to main content

Connect to the server

Your app must establish a connection to the Nexconn server before it can send and receive messages. The server validates the access token included in the connection request to authenticate the user.

Prerequisites

  • Obtain an access token by calling the Register a user Server API from your app server. The client SDK does not provide a method to obtain tokens.
    • After obtaining a token, the client can cache it locally for future connections. If the token is still valid, there is no need to request a new one.
    • Token expiration can be configured in the Console. Even after generating a new token, unexpired old tokens remain valid. To revoke a token, call the Expire token Server API.
  • Set up a connection status listener before connecting.
  • Initialize the SDK first.
warning

Never call the Server API directly from the client to obtain tokens. Doing so would expose the App Key and App Secret.

Connect

Choose the appropriate timing to connect based on your app's flow, for example after login or registration.

tip
  • Call connect only after SDK initialization. Otherwise, callbacks may not fire.
  • The SDK reconnects automatically after transient network interruptions until you explicitly disconnect.

API reference

swift
import NexconnChatSDK

static func connect(
params: ConnectParams,
databaseOpenedHandler: ((_ isRecreated: Bool, _ error: NCError?) -> Void)?,
completionHandler: ((_ userId: String?, _ error: NCError?) -> Void)?
)
ParameterTypeRequiredDescription
paramsNCConnectParamsYesConnection parameters. Use initWithToken: to set the access token. Set timeout for timeout behavior.
databaseOpenedHandlerBlockNoDatabase opened callback. error == nil means the database opened successfully. isRecreated == YES indicates the local database was recreated and local data was cleared.
completionHandlerBlockNoCompletion callback. Returns the current user ID on success, or NCError on failure.

Example

swift
import NexconnChatSDK

let params = ConnectParams(token: "your_access_token")
params.timeout = 30

NCEngine.connect(
params: params,
databaseOpenedHandler: { isRecreated, error in
guard error == nil else {
print("Database open failed: \(error!.localizedDescription)")
return
}

if isRecreated {
print("Local data was cleared; reload from remote if needed.")
}
},
completionHandler: { userId, error in
if let error {
print("Connection failed: \(error.localizedDescription)")
} else {
print("Connected, userId: \(userId ?? "")")
}
}
)

Connection status codes

The NCError.errorCode in the connection callback and the NCConnectionStatus enum values used in connection status monitoring:

tip
  1. When you receive NCConnectionStatusTokenIncorrect, request a new token from your server and reconnect. Avoid infinite loops.
  2. Callbacks are dispatched on an internal SDK queue. Switch to the main thread for UI updates.
Enum valueRaw valueDescriptionRecommended action
NCConnectionStatusConnected0Connected successfully
NCConnectionStatusNetworkUnavailable1Device network unavailableWait for network recovery. The SDK reconnects automatically.
NCConnectionStatusKickedOfflineByOtherClient6Kicked offline by another deviceReturn to the login screen and notify the user.
NCConnectionStatusConnecting10ConnectingShow a loading indicator if needed.
NCConnectionStatusUnconnected11Connection failed or not connectedHandle based on your app logic and error code.
NCConnectionStatusSignOut12Signed out
NCConnectionStatusSuspend13Connection suspended. The SDK reconnects when appropriate.
NCConnectionStatusTimeout14Reconnection timed out after the configured timeout.Prompt the user to reconnect manually.
NCConnectionStatusTokenIncorrect15Token invalid or expired.Request a new token and reconnect.
NCConnectionStatusDisconnException16Disconnected because the account was banned.Return to the login screen and notify the user.
NCConnectionStatusProxyUnavailable17Proxy service unavailableCheck proxy configuration and reconnect.
NCConnectionStatusUserAbandon19User account deactivatedReturn to the login screen and notify the user.