> ## Documentation Index
> Fetch the complete documentation index at: https://docs.quickblox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Connection

> Learn how to connect to the chat server and set connection settings.

## Before you begin

1. Register a [QuickBlox account](https://admin.quickblox.com/signin). This is a matter of a few minutes and you will be able to use this account to build your apps.
2. Configure QuickBlox SDK for your app. Check out [Setup](/sdks/ios-setup) page for more details.
3. Create a user session to be able to use QuickBlox functionality. See [Authentication](/sdks/ios-authentication) page to learn how to do it.

Visit [Key Concepts](/docs/key-concepts) page to learn the most important QuickBlox concepts.

## Connect to chat server

To connect to the chat server use the code snippet below.

<Tabs>
  <Tab title="Swift">
    ```Swift theme={null}
    let currentUser = QBUUser()
    currentUser.ID = 56
    currentUser.password = "chatUserPass"
    QBChat.instance.connect(withUserID: currentUser.id, password: currentUser.password, completion: { (error) in

    })
    ```
  </Tab>

  <Tab title="Objective-C">
    ```Objective-C theme={null}
    QBUUser *currentUser = [QBUUser user];
    currentUser.ID = 56;
    currentUser.password = @"chatUserPass";
    [QBChat.instance connectWithUserID:currentUser.ID password:currentUser.password completion:^(NSError * _Nullable error) {

    }];
    ```
  </Tab>
</Tabs>

Use `QBChatDelegate` to handle different connection states.

<Tabs>
  <Tab title="Swift">
    ```Swift theme={null}
    class YourClass : NSObject {
        QBChat.instance.addDelegate(self)
    }
    // MARK: QBChatDelegate
    extension YourClass : QBChatDelegate {
        func chatDidConnect() {
        }
        func chatDidReconnect() {
        }
        func chatDidDisconnectWithError(_ error: Error?) {
        }
        func chatDidNotConnectWithError(_ error: Error) {
        }
    }
    ```
  </Tab>

  <Tab title="Objective-C">
    ```Objective-C theme={null}
    @interface YourClass () <QBChatDelegate>
    @end

    @implementation YourClass
    - (instancetype)init {
        self = [super init];
        if (self) {
            [QBChat.instance addDelegate:self];
        }
        return self;
    }
    // MARK: QBChatDelegate
    - (void)chatDidConnect {
    }
    - (void)chatDidReconnect {
    }
    - (void)chatDidDisconnectWithError:(NSError *)error {
    }
    - (void)chatDidNotConnectWithError:(NSError *)error {
    }
    - (void)chatDidFailWithStreamError:(NSError *)error {
    }

    @end;
    ```
  </Tab>
</Tabs>

## Connect to chat server with QuickBlox session token

In case, you authenticate with QuickBlox via Firebase, Facebook, or Custom Identity Provider, you should connect to the chat server with QuickBlox user session token and QuickBlox user ID.

As a result of successful authentication via Firebase, Facebook, or Custom Identity Provider, you receive a QuickBlox user session token and QuickBlox user ID. Use QuickBlox user session token as a password and QuickBlox user ID as a login to connect to the chat server.

<Warning>
  Don't use the Firebase/Facebook access token as a password to connect to the chat server. You will receive the following runtime error in this case: `<failure xmlns="urn:ietf:params:xml:ns:xmpp-sasl"><not-authorized/><text xml:lang='en'>Password not verified</text></failure>`.
</Warning>

<Tabs>
  <Tab title="Swift">
    ```Swift theme={null}
    let userID = QBSession.current.currentUserID
    let userPassword = QBSession.current.sessionDetails?.token

    QBChat.instance.connect(withUserID: userID, password: userPassword, completion: { (error) in

    })
    ```
  </Tab>

  <Tab title="Objective-C">
    ```Objective-C theme={null}
    NSUInteger userID = QBSession.currentSession.currentUserID;
    NSString *userPassword = QBSession.currentSession.sessionDetails.token;

    [QBChat.instance connectWithUserID:userID password:userPassword completion:^(NSError * _Nullable error) {

    }];
    ```
  </Tab>
</Tabs>

| Argument     | Required | Description                                                         |
| ------------ | -------- | ------------------------------------------------------------------- |
| userID       | yes      | The ID of a user                                                    |
| userPassword | yes      | Specifies an active QuickBlox user session token set as a password. |

## Disconnect from chat server

Disconnect from the chat server using the snippet below.

<Tabs>
  <Tab title="Swift">
    ```Swift theme={null}
    QBChat.instance.disconnect { (error) in

    }
    ```
  </Tab>

  <Tab title="Objective-C">
    ```Objective-C theme={null}
    [QBChat.instance disconnectWithCompletionBlock:^(NSError * _Nullable error) {

    }];
    ```
  </Tab>
</Tabs>

## Enable auto-reconnect to chat

Auto-reconnect is turned off by default. If you want the SDK to automatically reconnect to the chat server when the connection is lost, just enable this option:

<Tabs>
  <Tab title="Swift">
    ```Swift theme={null}
    QBSettings.autoReconnectEnabled = true
    ```
  </Tab>

  <Tab title="Objective-C">
    ```Objective-C theme={null}
    QBSettings.autoReconnectEnabled = YES;
    ```
  </Tab>
</Tabs>

Once enabled, the SDK will handle reconnection automatically, no additional code needed.

## Manage chat connections

To provide a seamless chat experience, our SDK manages connections to the chat server at an application-wide level. Thus, to handle [offline messages](/sdks/ios-chat-offline-messaging) correctly, use the `disconnect()` method when an app goes to the background and `connect()` method when an app goes to the foreground. As a result, the SDK will disconnect/connect the current user from the chat server when the app goes to the background/foreground mode.

<Tabs>
  <Tab title="Swift">
    ```Swift theme={null}
    class AppDelegate: UIResponder, UIApplicationDelegate {
        // ...
        func applicationWillTerminate(_ application: UIApplication) {
            QBChat.instance.disconnect { (error) in
            }
        }
        func applicationDidEnterBackground(_ application: UIApplication) {
            QBChat.instance.disconnect { (error) in
            }
        }
        func applicationWillEnterForeground(_ application: UIApplication) {
            QBChat.instance.connect(withUserID: currentUser.ID, password: currentUser.password) { (error) in
            }
        }
        // ...
    }
    ```
  </Tab>

  <Tab title="Objective-C">
    ```Objective-C theme={null}
    @implementation AppDelegate
    // ...
    - (void)applicationWillTerminate:(UIApplication *)application {
        [QBChat.instance disconnectWithCompletionBlock:^(NSError * _Nullable error) {
        }];
    }
    - (void)applicationDidEnterBackground:(UIApplication *)application {
        [QBChat.instance disconnectWithCompletionBlock:^(NSError * _Nullable error) {
        }];
    }
    - (void)applicationWillEnterForeground:(UIApplication *)application {
        [QBChat.instance connectWithUserID:currentUser.ID password:currentUser.password completion:^(NSError * _Nullable error) {
        }];
    }
    // ...
    ```
  </Tab>
</Tabs>

## Set connection settings

Use the settings below to configure the connection to the chat server.

<Tabs>
  <Tab title="Swift">
    ```Swift theme={null}
    QBSettings.autoReconnectEnabled = true
    QBSettings.carbonsEnabled = true
    QBSettings.keepAliveInterval = 20
    QBSettings.streamManagementSendMessageTimeout = 0
    QBSettings.networkIndicatorManagerEnabled = false
    ```
  </Tab>

  <Tab title="Objective-C">
    ```Objective-C theme={null}
    [QBSettings setAutoReconnectEnabled:YES];
    [QBSettings setReconnectTimerInterval:5];
    [QBSettings setCarbonsEnabled:YES];
    [QBSettings setKeepAliveInterval:20];
    [QBSettings setStreamManagementSendMessageTimeout:0];
    [QBSettings setNetworkIndicatorManagerEnabled:NO];
    ```
  </Tab>
</Tabs>

| Parameters                         | Description                                                                                                                                                                                                         |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| autoReconnectEnabled               | iOS SDK reconnects automatically to the chat server when the connection to the server is lost. Default: **false**.                                                                                                  |
| reconnectTimerInterval             | A reconnect timer can **optionally** be used to attempt a reconnect periodically. Set in seconds. Default: **5**.                                                                                                   |
| carbonsEnabled                     | Message carbons allow for real-time message syncing between devices. Default: **false**.                                                                                                                            |
| keepAliveInterval                  | Keep-alive option for a socket connection. Keep-alive is the option allowing to detect a stale connection. Set in seconds. Default: **20**.                                                                         |
| streamManagementSendMessageTimeout | The timeout value for stream management. Set in seconds. If this parameter is greater than 0, then it is applied, otherwise, it is not applied. Default: **0**.                                                     |
| networkIndicatorManagerEnabled     | A boolean value indicating whether the manager is enabled. If **true**, the manager will change status bar network activity indicator according to network operation notifications it receives. Default: **false**. |
