Skip to main content

Monitor connection status

Use the connection status APIs to react to reconnects, offline kicks, token failures, and other connection-state changes.

Listen for connection status changes

Register a ConnectionStatusHandler after SDK initialization and before connecting.

swift
import NexconnChatSDK

NCEngine.addConnectionStatusHandler(identifier: "MyConnectionHandler", handler: self)

Implement the protocol. In the current SDK, the callback receives a ConnectionStatusChangedEvent wrapper, and the actual connection state is on event.status.

swift
import NexconnChatSDK

final class ConnectionMonitor: NSObject, ConnectionStatusHandler {
func onConnectionStatusChanged(_ event: ConnectionStatusChangedEvent) {
switch event.status {
case .connected:
print("Connected successfully.")
case .networkUnavailable:
print("Network unavailable. The SDK will reconnect automatically.")
case .tokenIncorrect:
// Request a new token from your server and reconnect.
break
case .kickedOfflineByOtherClient:
print("Kicked offline by another device.")
default:
print("Connection status changed: \(event.status.rawValue)")
}
}
}

Remove the handler when it is no longer needed:

swift
import NexconnChatSDK

NCEngine.removeConnectionStatusHandler(forIdentifier: "MyConnectionHandler")

Get the current connection status

Call getConnectionStatus() at any time to retrieve the current IM connection state:

swift
import NexconnChatSDK

let status = NCEngine.getConnectionStatus()

Handle status in the connect callback

When establishing a connection, handle NCError.errorCode in the error callback:

swift
import NexconnChatSDK

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

NCEngine.connect(
params: params,
databaseOpenedHandler: { _, error in
if let error {
print("Database open failed: \(error.localizedDescription)")
}
},
completionHandler: { userId, error in
guard error == nil else {
switch error!.errorCode {
case 15:
print("Token is invalid or expired.")
case 14:
print("Connection timed out.")
default:
print("Connection failed: \(error!.errorCode)")
}
return
}

print("Connected successfully, userId: \(userId ?? "")")
}
)