> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-ios-ui-kit-sdk-fixes.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Connection Behaviour

> Understanding the default WebSocket connection behavior of the CometChat iOS SDK during login and app lifecycle.

<Info>
  **Quick Reference for AI Agents & Developers**

  * **On login:** SDK automatically creates WebSocket connection
  * **On logout:** SDK disconnects WebSocket
  * **Background:** Connection maintained based on app settings
  * **Reconnection:** Automatic reconnection on network recovery
  * **Related:** [Connection Status](/sdk/ios/connection-status) · [Managing WebSocket Manually](/sdk/ios/managing-web-socket-connections-manually) · [Setup](/sdk/ios/setup)
</Info>

### Default SDK behaviour

When the login method of the SDK is called, the SDK performs the below operations:

1. Logs the user into the SDK
2. Saves the details of the logged in user locally.
3. Creates a web-socket connection for the logged in user.

This makes sure that the logged in user starts receiving real-time messages sent to him or any groups that he is a part of as soon as he logs in.

When the app is reopened, and the init() method is called, the web-socket connection to the server is established automatically.

And as soon as the app gets into background, web sockets will get disconnected. It will get reconnected when the app comes on foreground from the background.

This is the default behaviour of the CometChat SDKs. However, if you wish to take control of the web-socket connection i.e if you wish to connect and disconnect to the web-socket server manually, you can refer to the Managing Web-socket Connection section.

### Auto Mode

CometChat SDK default connection behaviour is auto mode. Auto mode, the SDK automatically establishes and maintains the WebSocket connection. You do not need to explicitly call any methods to do this.

To enable auto mode, you need to set the `autoEstablishSocketConnection()` method of AppSettings builder class to `true`. If you do not set this, the SDK will automatically apply the auto mode as the default behaviour for the WebSocket connection.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-docs-ios-ui-kit-sdk-fixes/aAidEvd1OC-tkQUy/images/c8c546a3-x8a7yv541r6b9g8t73h9j3afh1p4cgsopv6yj238ebz8565rscv568a40zf34f5h-c617ae8f9a6f09edf27d37dd01ce1bf3.png?fit=max&auto=format&n=aAidEvd1OC-tkQUy&q=85&s=be8c8a3c121a5308e9a6b77f0d9a4c03" width="683" height="162" data-path="images/c8c546a3-x8a7yv541r6b9g8t73h9j3afh1p4cgsopv6yj238ebz8565rscv568a40zf34f5h-c617ae8f9a6f09edf27d37dd01ce1bf3.png" />
</Frame>

| App State         | Behaviour                               |
| ----------------- | --------------------------------------- |
| App in foreground | Connected with WebSocket                |
| App in background | Immediately disconnected with WebSocket |

### Reconnection

If the app is in the foreground and there is no internet connection, the SDK will handle the reconnection of the WebSocket in auto mode.

## Manual Mode SDK behaviour

In manual mode, you have to explicitly establish and disconnect the WebSocket connection. To do this, you need to set the `autoEstablishSocketConnection()` method to `false` and then call the `CometChat.connect()` method to establish the connection and the `CometChat.disconnect()` method to disconnect the connection.

Manual mode provides an advantage of being connected to the web-sockets even if the app is in background. But this needs to be handled by the user according to there need with the help of **ping()** function.

By default, if manual mode is activated, the SDK will disconnect the WebSocket connection after 30 seconds if the app goes into the background. This means that the WebSocket connection will remain alive for 30 seconds after the app goes into the background, but it will be disconnected after that time if no pings are received.

To keep the WebSocket connection alive even if your app goes in the background, you need to call the `CometChat.ping()` method from your app within 30 seconds. This method sends a ping message to the CometChat server, which tells the server that the app is still active.

You have to continue calling CometChat.ping() function every 30 seconds till the time you need your web-sockets to be connected.

If you do not call the `CometChat.ping()` method within 30 seconds, the SDK will disconnect the WebSocket connection. This means that you will lose any messages that are sent to your app while it is in the background.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-docs-ios-ui-kit-sdk-fixes/OIUJPqkRTDwLak2K/images/42540588-t1mk6nfkkpy7fipuzeupl1oognnhmjuw3vdivlhg0t8turw7okuiwenncydrc83q-4ab4b9056ff91b946fb2fc048bc764fa.png?fit=max&auto=format&n=OIUJPqkRTDwLak2K&q=85&s=17a2dd08a2c258ef2f5a981d9ba2f948" width="1012" height="434" data-path="images/42540588-t1mk6nfkkpy7fipuzeupl1oognnhmjuw3vdivlhg0t8turw7okuiwenncydrc83q-4ab4b9056ff91b946fb2fc048bc764fa.png" />
</Frame>

| App State         | Behaviour                                                                                                          |
| ----------------- | ------------------------------------------------------------------------------------------------------------------ |
| App in foreground | Call `CometChat.connect()` to create the WebSocket connection.                                                     |
| App in background | Disconnect the WebSocket connection if no ping is received within 30 seconds after the app goes in the background. |

## Managing Manually

The CometChat SDK also allows you to modify the above default behaviour of the SDK and take the control of the web-socket connection into your own hands. In order to achieve this, you need to follow the below steps:

### Enable Manual Mode

While calling the init() function on the app startup, you need to inform the SDK that you will be managing the web socket connect. You can do so by using the `autoEstablishSocketConnection()` method provided by the `AppSettingsBuilder` class. This method takes a boolean value as an input. If set to `true` , the SDK will manage the web-socket connection internally based on the default behaviour mentioned above. If set to `false` , the web socket connection can will not be managed by the SDK and you will have to handle it manually. You can refer to the below code snippet for the same:

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    let appId = "your_App_ID" 
    let region = "us"
      
    let mySettings = AppSettings.AppSettingsBuilder()
        .subscribePresenceForAllUsers()
        .setRegion(region: region)
        .autoEstablishSocketConnection(false) //call this function 
        .build()


    CometChat.init(appId: appID ,appSettings: mySettings,onSuccess: { (isSuccess) in }) {
        print("CometChatSDK initialise success")
    }) { (error) in 
        print("CometChatSDK initialise failed with error: \(error.errorDescription)")
    }
    ```
  </Tab>
</Tabs>

You can manage the connection to the web-socket server using the `connect()` , `disconnect()` and `ping()` methods provided by the SDK.

### Connect to the web-socket server

You need to use the `connect()` method provided by the `CometChat` class to establish the connection to the web-socket server. Please make sure that the user is logged in to the SDK before calling this method. You can use the CometChat.getLoggedInUser() method to check this. Once the connection is established, you will start receiving all the real-time events for the logged in user

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    CometChat.connect {
        print("CometChat Connect success")
    } onError: { error in
        print("CometChat Connect failed with error: \(error.errorDescription)")
    }
    ```
  </Tab>
</Tabs>

<Accordion title="Sample Payload - Connect to WebSocket">
  **Prerequisites:**

  | Requirement    | Description                                               |
  | -------------- | --------------------------------------------------------- |
  | User logged in | `CometChat.getLoggedInUser() != nil`                      |
  | Manual mode    | `autoEstablishSocketConnection(false)` set in AppSettings |

  **Success Response:**

  | Parameter | Type | Description                                                    |
  | --------- | ---- | -------------------------------------------------------------- |
  | Callback  | Void | Success callback invoked when WebSocket connection established |

  **After Connect:**

  | Effect            | Description                                                   |
  | ----------------- | ------------------------------------------------------------- |
  | Real-time events  | Start receiving messages, typing indicators, presence updates |
  | Connection status | WebSocket connected                                           |

  **Error Response ([CometChatException](#common-error-codes)):**

  | Parameter        | Type   | Description                                                                                                   |
  | ---------------- | ------ | ------------------------------------------------------------------------------------------------------------- |
  | errorCode        | String | Unique error code. Example: `"ERROR_WEBSOCKETS_ALLREADY_IN_CONNECTED_STATE"`                                  |
  | errorDescription | String | Human-readable error message. Example: `"Web sockets connect called while web sockets are already connected"` |
</Accordion>

### Disconnect from the web-socket server

You can use the `disconnect()` method provided by the `CometChat` class to break the established connection. Once the connection is broken, you will stop receiving all the real-time events for the logged in user.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    CometChat.disconnect {
        print("CometChat Connect success")
    } onError: { error in
        print("CometChat Connect failed with error: \(error.errorDescription)")
    }
    ```
  </Tab>
</Tabs>

<Accordion title="Sample Payload - Disconnect from WebSocket">
  **Effect:**

  | Action           | Description                                                  |
  | ---------------- | ------------------------------------------------------------ |
  | WebSocket closed | Connection to server terminated                              |
  | Real-time events | Stop receiving messages, typing indicators, presence updates |
  | Reconnection     | Must call `connect()` to re-establish connection             |

  **Success Response:**

  | Parameter | Type | Description                                          |
  | --------- | ---- | ---------------------------------------------------- |
  | Callback  | Void | Success callback invoked when WebSocket disconnected |

  **After Disconnect:**

  | Effect          | Description                             |
  | --------------- | --------------------------------------- |
  | Status          | WebSocket disconnected                  |
  | Events          | No real-time events received            |
  | Action required | Call `CometChat.connect()` to reconnect |
</Accordion>

### Maintain long-standing background connection

<Note>
  To ensure that the WebSocket connection is always alive, you can create a service or background service that calls the `CometChat.ping()` method in a loop. This will ensure that the ping message is sent to the server every 30 seconds, even if the app is not in the foreground.
</Note>

You can maintain a long-standing background connection event when your app is in the background, call the `CometChat.ping()` method every 30 seconds of your app entering the background or after the previous ping() call.

<Tabs>
  <Tab title="Swift">
    ```swift theme={null}
    CometChat.ping {
        print("Manual Ping OnSuccess received")
    } onError: { error in
        print("Got an error while sending the ping: \(error.errorDescription)")
    }
    ```
  </Tab>
</Tabs>

<Accordion title="Sample Payload - Ping (Keep Alive)">
  **Purpose:**

  | Action     | Description                                             |
  | ---------- | ------------------------------------------------------- |
  | Keep alive | Maintains WebSocket connection in background            |
  | Frequency  | Must be called every 30 seconds in background           |
  | Timeout    | Connection drops if ping not received within 30 seconds |

  **Success Response:**

  | Parameter | Type | Description                                     |
  | --------- | ---- | ----------------------------------------------- |
  | Callback  | Void | Success callback invoked when ping acknowledged |

  **Error Response ([CometChatException](#common-error-codes)):**

  | Parameter        | Type   | Description                                                                                                    |
  | ---------------- | ------ | -------------------------------------------------------------------------------------------------------------- |
  | errorCode        | String | Unique error code. Example: `"ERROR_PING_NOT_AVAILABLE"`                                                       |
  | errorDescription | String | Human-readable error message. Example: `"Ping function is not available when auto establish web socket is on"` |

  **Background Strategy Example:**

  ```swift theme={null}
  // In AppDelegate or SceneDelegate:
  var pingTimer: Timer?

  func applicationDidEnterBackground(_ application: UIApplication) {
      // Start pinging every 25 seconds (before 30 sec timeout)
      pingTimer = Timer.scheduledTimer(withTimeInterval: 25, repeats: true) { _ in
          CometChat.ping {
              print("Background ping successful")
          } onError: { error in
              print("Ping failed: \(error?.errorDescription)")
          }
      }
  }

  func applicationWillEnterForeground(_ application: UIApplication) {
      // Stop pinging when returning to foreground
      pingTimer?.invalidate()
      pingTimer = nil
  }
  ```
</Accordion>

## Reconnection

If manual mode is enabled and the app is in the foreground, the SDK will automatically reconnect the WebSocket if the internet connection is lost. However, if the app is in the background and the WebSocket is disconnected or you called `CometChat.disconnect()`, then you will need to call the `CometChat.connect()` method to create a new WebSocket connection.

***

## Common Error Codes

| Error Code                                        | Description                 | Resolution                                                     |
| ------------------------------------------------- | --------------------------- | -------------------------------------------------------------- |
| ERROR\_WEBSOCKETS\_ALLREADY\_IN\_CONNECTED\_STATE | WebSocket already connected | No action needed, connection exists                            |
| ERROR\_PING\_NOT\_AVAILABLE                       | Ping called in auto mode    | Enable manual mode with `autoEstablishSocketConnection(false)` |
| ERR\_NOT\_LOGGED\_IN                              | No user is logged in        | Call `CometChat.login()` first                                 |
| ERR\_WEBSOCKET\_ERROR                             | WebSocket connection error  | Check network connectivity                                     |
| ERR\_NO\_INTERNET                                 | No internet connection      | Wait for network recovery or retry                             |
