Monitor connection status
The Nexconn Chat SDK provides methods to retrieve and respond to IM connection status changes.
Listen for connection status changes
Register a ConnectionStatusHandler to receive callbacks whenever the connection status changes. Register the handler after initializing the SDK and before connecting.
- Swift
- Objective-C
import NexconnChatSDK
NCEngine.addConnectionStatusHandler(identifier: "MyConnectionHandler", handler: self)
[NCEngine addConnectionStatusHandlerWithIdentifier:@"MyConnectionHandler" handler:self];
Implement the ConnectionStatusHandler protocol. In the current SDK, the callback receives a ConnectionStatusChangedEvent wrapper, and the actual state is available on event.status:
- Swift
- Objective-C
import NexconnChatSDK
final class ConnectionMonitor: NSObject, ConnectionStatusHandler {
func onConnectionStatusChanged(_ event: ConnectionStatusChangedEvent) {
switch event.status {
case .connected:
print("Connected successfully.")
case .networkUnavailable:
print("Network unavailable; SDK will reconnect automatically.")
case .tokenIncorrect:
// Retrieve a new access token from your server and reconnect.
break
case .kickedOfflineByOtherClient:
print("Kicked offline by another device.")
default:
print("Connection status changed: \(event.status.rawValue)")
}
}
}
- (void)onConnectionStatusChanged:(NCConnectionStatusChangedEvent *)event {
switch (event.status) {
case NCConnectionStatusConnected:
NSLog(@"Connected successfully.");
break;
case NCConnectionStatusNetworkUnavailable:
NSLog(@"Network unavailable; SDK will reconnect automatically.");
break;
case NCConnectionStatusTokenIncorrect:
// Retrieve a new access token from your server and reconnect
break;
case NCConnectionStatusKickedOfflineByOtherClient:
NSLog(@"Kicked offline by another device.");
break;
default:
NSLog(@"Connection status changed: %ld", (long)event.status);
break;
}
}
To remove the handler when it is no longer needed:
- Swift
- Objective-C
import NexconnChatSDK
NCEngine.removeConnectionStatusHandler(forIdentifier: "MyConnectionHandler")
[NCEngine removeConnectionStatusHandlerForIdentifier:@"MyConnectionHandler"];
Get the current connection status
Call getConnectionStatus() at any time to actively retrieve the current IM connection status.
- Swift
- Objective-C
import NexconnChatSDK
let status = NCEngine.getConnectionStatus()
NCConnectionStatus status = [NCEngine getConnectionStatus];
NCConnectionStatus enum
NCConnectionStatus defines all possible states during the IM connection lifecycle. The table below describes the key states your app needs to handle:
| Value (ObjC) | rawValue | Description | Recommended Action |
|---|---|---|---|
NCConnectionStatusUnknown | -1 | Unknown status. The SDK usually reconnects automatically. | — |
NCConnectionStatusConnected | 0 | Connected successfully. | — |
NCConnectionStatusNetworkUnavailable | 1 | Current device network is unavailable. The SDK will reconnect automatically when the network recovers. | Display a network error indicator in the UI. |
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. | Show a loading indicator. |
NCConnectionStatusUnconnected | 11 | Connection failed or not connected. | Notify the user based on your app's business logic. |
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 client SDK and app server use different App Keys, or if the token has exceeded the expiry set in the console. | 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. No further reconnection attempts will be made. | Navigate to the login screen and notify the user that the account has been deactivated. |
Handle status in connection callbacks
When establishing a connection, use completionHandler to receive the connection result. Handle NCError.errorCode in the error callback:
- Swift
- Objective-C
import NexconnChatSDK
let params = ConnectParams(token: "your_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 recreated. Reload remote data if needed.")
}
},
completionHandler: { userId, error in
guard error == nil else {
switch error!.errorCode {
case 15:
print("Token is invalid or expired. Request a new token and reconnect.")
case 14:
print("Connection timed out. Prompt the user to retry.")
default:
print("Connection failed, error code: \(error!.errorCode)")
}
return
}
print("Connected successfully, user ID: \(userId)")
}
)
NCConnectParams *params = [[NCConnectParams alloc] initWithToken:@"your_token"];
params.timeout = 30;
[NCEngine connectWithParams:params
databaseOpenedHandler:^(BOOL isRecreated, NCError * _Nullable error) {
if (error == nil) {
if (isRecreated) {
NSLog(@"Local data was recreated. Reload remote data if needed.");
}
}
}
completionHandler:^(NSString *userId, NCError * _Nullable error) {
if (error == nil) {
NSLog(@"Connected successfully, user ID: %@", userId);
} else {
switch (error.errorCode) {
case 15:
// Retrieve a new access token and reconnect
break;
case 14:
// Connection timed out — notify the user
break;
default:
NSLog(@"Connection failed, error code: %ld", (long)error.errorCode);
break;
}
}
}];