> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-agent-in-group-react-v6.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.

<Accordion title="AI Integration Quick Reference">
  * **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)
</Accordion>

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

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.

If you wish to take control of the web-socket connection manually, refer to the [Managing Web-socket Connection](/sdk/ios/managing-web-socket-connections-manually) section.

### Auto Mode

CometChat SDK default connection behaviour is auto mode. The SDK automatically establishes and maintains the WebSocket connection.

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

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-docs-agent-in-group-react-v6/-4h3cKAJUX2gQz_u/images/automatic-web-socket-handling.png?fit=max&auto=format&n=-4h3cKAJUX2gQz_u&q=85&s=73c4ee54f5f07b3ce7dec636a06333f8" alt="CometChat automatic WebSocket handling flow showing login, automatic connection, background disconnect, and auto reconnect on return to foreground" width="1537" height="1023" data-path="images/automatic-web-socket-handling.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 explicitly establish and disconnect the WebSocket connection. Set `autoEstablishSocketConnection()` to `false` and then call `CometChat.connect()` to establish the connection and `CometChat.disconnect()` to disconnect.

Manual mode provides an advantage of being connected to the web-sockets even if the app is in background. This needs to be handled by the user with the help of the **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.

To keep the WebSocket connection alive in the background, call the `CometChat.ping()` method from your app within 30 seconds. Continue calling `CometChat.ping()` every 30 seconds as long as you need the web-sockets connected.

If you do not call `CometChat.ping()` within 30 seconds, the SDK will disconnect the WebSocket connection.

<Frame>
  <img src="https://mintcdn.com/cometchat-22654f5b-docs-agent-in-group-react-v6/NKRwOrdYfqQN0SpG/images/manual-web-socket-connection-handling.png?fit=max&auto=format&n=NKRwOrdYfqQN0SpG&q=85&s=e929b297035d6c472cacc51b035fbcd5" alt="CometChat manual WebSocket handling flow showing manual connect, 30-second background timeout, ping keep alive, optional disconnect, and reconnect flow" width="1522" height="1033" data-path="images/manual-web-socket-connection-handling.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

### Enable Manual Mode

While calling the init() function on the app startup, use the `autoEstablishSocketConnection()` method provided by the `AppSettingsBuilder` class. If set to `true`, the SDK manages the web-socket connection internally. If set to `false`, you handle it manually:

<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

Use the `connect()` method provided by the `CometChat` class to establish the connection. Make sure the user is logged in before calling this method (`CometChat.getLoggedInUser()`). Once connected, you will start receiving all real-time events.

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

### Disconnect from the web-socket server

Use the `disconnect()` method to break the established connection. Once disconnected, you will stop receiving all real-time events.

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

### Maintain long-standing background connection

You can maintain a long-standing background connection by calling the `CometChat.ping()` method every 30 seconds after your app enters 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>

## 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 `CometChat.connect()` 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                             |

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Connection Status" icon="signal" href="/sdk/ios/connection-status">
    Monitor the SDK connection state in real time
  </Card>

  <Card title="Managing WebSocket Manually" icon="sliders" href="/sdk/ios/managing-web-socket-connections-manually">
    Take full control of WebSocket connections
  </Card>

  <Card title="All Real-Time Delegates" icon="tower-broadcast" href="/sdk/ios/all-real-time-delegates-listeners">
    Complete reference for all SDK event delegates
  </Card>

  <Card title="Background Updates" icon="mobile-screen" href="/sdk/ios/prepare-your-app-for-background-updates">
    Keep real-time connection alive in background
  </Card>
</CardGroup>
