> ## Documentation Index
> Fetch the complete documentation index at: https://cometchat-22654f5b-docs-rn-guide-message-privately.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Methods

> Reference for CometChatUIKit wrapper methods that manage SDK operations, internal eventing, login, logout, user creation, and message sending in the iOS UI Kit.

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

  * **Class:** `CometChatUIKit`
  * **Import:** `import CometChatUIKitSwift`
  * **Init:** `CometChatUIKit.init(uiKitSettings:onSuccess:onError:)`
  * **Login:** `CometChatUIKit.login(uid:onSuccess:onError:)` or `CometChatUIKit.login(authToken:onSuccess:onError:)`
  * **Logout:** `CometChatUIKit.logout(user:result:)`
  * **Create user:** `CometChatUIKit.createUser(user:onSuccess:onError:)`
  * **Send message:** `CometChatUIKit.sendTextMessage(message:onSuccess:onError:)`, `sendMediaMessage`, `sendCustomMessage`
  * **Related:** [Getting Started](/ui-kit/ios/getting-started) · [Events](/ui-kit/ios/events) · [SDK Overview](/sdk/ios/overview)
</Info>

## Overview

The UI Kit's core function is to extend the [CometChat SDK](/sdk/ios/overview), translating raw data and functionality into visually appealing, easy-to-use UI components.

To effectively manage and synchronize UI elements and data across all components, the UI Kit uses internal events. These events enable real-time change tracking and ensure the UI reflects the most current state of data.

The CometChat UI Kit encapsulates critical [CometChat SDK](/sdk/ios/overview) methods within its wrapper to efficiently manage internal eventing. This abstraction layer simplifies interaction with the underlying SDK, making it more developer-friendly.

## Methods

Access all public methods exposed by the CometChat UI Kit through the `CometChatUIKit` class.

### Init

You must invoke this method before using any other UI Kit methods. This initialization ensures the UI Kit and Chat SDK function correctly in your application. Best practice is to make this one of the first lines of code executed in your application's lifecycle.

<Note>
  Replace **APP\_ID**, **REGION**, and **AUTH\_KEY** with your CometChat App ID, Region, and Auth Key. The `Auth Key` is an optional property of the `UIKitSettings` class, intended primarily for proof-of-concept (POC) development or early stages of application development. For production, use [Auth Token](#login-using-auth-token) instead.
</Note>

#### UIKitSettings Properties

| Method                               | Type                          | Description                                                                                                                           |
| ------------------------------------ | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| **set(appID:)**                      | `String`                      | Sets the unique ID for the app, available on dashboard                                                                                |
| **set(region:)**                     | `String`                      | Sets the region for the app ('us' or 'eu')                                                                                            |
| **set(authKey:)**                    | `String`                      | Sets the auth key for the app, available on dashboard                                                                                 |
| **subscribePresenceForAllUsers**     | `String`                      | Sets subscription type for tracking the presence of all users                                                                         |
| **subscribePresenceForFriends**      | `String`                      | Sets subscription type for tracking the presence of friends                                                                           |
| **subscribePresenceForRoles**        | `String`                      | Sets subscription type for tracking the presence of users with specified roles                                                        |
| **setAutoEstablishSocketConnection** | `Boolean`                     | Configures if web socket connections will established automatically on app initialization or be done manually, set to true by default |
| **setAIFeatures**                    | `List<AIExtensionDataSource>` | Sets the AI Features that need to be added in UI Kit                                                                                  |
| **setExtensions**                    | `List<ExtensionsDataSource>`  | Sets the list of extension that need to be added in UI Kit                                                                            |

#### Example

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    let uiKitSettings = UIKitSettings()
      .set(region: "your_region")
      .set(appID: "your_appId")
      .set(authKey: "your_authKey")
      .subscribePresenceForAllUsers()
      .autoEstablishSocketConnection(bool: true)

    CometChatUIKit.init(uiKitSettings: uikitSettings) { result in
      switch result{
      case .success(let bool):
        print( "Initialization success")
      case .failure(let error):
        print("CometChat exception: \(error)")
      }
    }
    ```
  </Tab>
</Tabs>

***

### Login using Auth Key

Only the `UID` of a user is needed to log in. This simple authentication procedure is useful for POC or development phases. For production apps, use [AuthToken](#login-using-auth-token) instead.

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    CometChatUIKit.login(uid: "uid") { (result) in
      switch result {
      case .success(let user):
        print("CometChat user logged in: \(user)")
      case .onError(let error):
        print("CometChat exception: \(error)")
      }
    }
    ```
  </Tab>
</Tabs>

***

### Login using Auth Token

This advanced authentication procedure does not use the Auth Key directly in your client code, ensuring better security.

1. [Create a User](/rest-api/chat-apis) via the CometChat API when the user signs up in your app.
2. [Create an Auth Token](/rest-api/chat-apis) via the CometChat API for the new user and save the token in your database.
3. Load the Auth Token in your client and pass it to the `login(authToken:)` method.

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    CometChatUIKit.login(authToken: "your_authToken") { (result) in
      switch result {
      case .success(let user):
        print("CometChat user logged in: \(user)")
      case .onError(let error):
        print("CometChat exception: \(error)")
      }
    }
    ```
  </Tab>
</Tabs>

***

### Logout

The CometChat UI Kit and Chat SDK handle the session of the logged-in user within the framework. Before a new user logs in, clean this data to avoid potential conflicts or unexpected behavior by invoking the `.logout(user:)` function.

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    let user = User(uid: "uid", name: "user_name")

    CometChatUIKit.logout(user: user) { (result) in
      switch result {
      case .success(let user):
        print("CometChat user logged out: \(user)")
      case .onError(let error):
        print("CometChat exception: \(error)")
      }
    }
    ```
  </Tab>
</Tabs>

***

### Create User

Dynamically create users on CometChat using the `.create(user:)` function. This is useful when users are registered or authenticated by your system and need to be created on CometChat.

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    let user = User(uid: "uid", name: "user_name")

    CometChatUIKit.create(user: user) { result in
      switch result {
      case .success(let user):
        print("CometChat user logged out: \(user)")
      case .onError(let error):
        print("CometChat exception: \(error)")
      }
    }
    ```
  </Tab>
</Tabs>

***

### Base Message

#### Text Message

To send a text message to a single user or a group, use the `sendTextMessage()` function. This function requires a `TextMessage` object containing the necessary information for delivering the message.

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    let textMessage = TextMessage(receiverUid: "uid", text: message, receiverType: .user)
    textMessage.muid =  "\(NSDate().timeIntervalSince1970)"
    textMessage.sentAt = Int(Date().timeIntervalSince1970)
    textMessage.senderUid = CometChat.getLoggedInUser()?.uid ?? ""
    textMessage.sender = CometChat.getLoggedInUser()
    textMessage.parentMessageId = parentMessageId

    CometChatUIKit.sendTextMessage(message: textMessage)
    ```
  </Tab>
</Tabs>

<Note>
  `CometChatUIKit.sendTextMessage()` automatically adds the message to the [MessagesComponent](/ui-kit/ios/message-list) and [ConversationsComponent](/ui-kit/ios/conversations), handling all related cases for you. In contrast, `CometChat.sendTextMessage()` only sends the message without updating these UI Kit components.
</Note>

***

#### Media Message

To send a media message to a single user or a group, use the `sendMediaMessage()` function. This function requires a `MediaMessage` object containing the necessary information for delivering the message.

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    let mediaMessage = MediaMessage(receiverUid: "uid", fileurl: url, messageType: type, receiverType: .user)
    mediaMessage.muid = "\(NSDate().timeIntervalSince1970)"
    mediaMessage.sentAt = Int(Date().timeIntervalSince1970)
    mediaMessage.sender = CometChat.getLoggedInUser()
    mediaMessage.metaData = ["fileURL": url]
    mediaMessage.senderUid = CometChat.getLoggedInUser()?.uid ?? ""
    mediaMessage.parentMessageId = parentMessageId

    CometChatUIKit.sendMediaMessage(message: MediaMessage)
    ```
  </Tab>
</Tabs>

<Note>
  `CometChatUIKit.sendMediaMessage()` automatically adds the message to the [MessagesComponent](/ui-kit/ios/message-list) and [ConversationsComponent](/ui-kit/ios/conversations), handling all related cases for you. In contrast, `CometChat.sendMediaMessage()` only sends the message without updating these UI Kit components.
</Note>

***

#### Custom Message

To send a custom message to a single user or a group, use the `sendCustomMessage()` function. This function requires a `CustomMessage` object containing the necessary information for delivering the message.

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    var customData = [String: Any]()
    customData["key"] = "value"

    let customMessage = CustomMessage(receiverUid: "uid or guid", receiverType: .user, customData: customData, type: "custom message type")
    customMessage.muid = "\(Int(Date().timeIntervalSince1970))"
    customMessage.senderUid = CometChat.getLoggedInUser()?.uid
    customMessage.sender = CometChat.getLoggedInUser()

    CometChatUIKit.sendCustomMessage(message: CustomMessage)
    ```
  </Tab>
</Tabs>

<Note>
  `CometChatUIKit.sendCustomMessage()` automatically adds the message to the [MessagesComponent](/ui-kit/ios/message-list) and [ConversationsComponent](/ui-kit/ios/conversations), handling all related cases for you. In contrast, `CometChat.sendCustomMessage()` only sends the message without updating these UI Kit components.
</Note>

***

### Interactive Message

#### Form Message

To send a Form message to a single user or a group, use the `sendFormMessage()` function. This function requires a `FormMessage` object containing the necessary information to create a form bubble for that message.

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    let apiAction = APIAction()
    apiAction.url = "https://example.com/api"
    apiAction.method = .POST

    let submitButton = ButtonElement()
    submitButton.elementId = "1"
    submitButton.action = apiAction
    submitButton.buttonText = "Submit"

    let nameInput = TextInput()
    nameInput.elementId = "1"
    nameInput.placeHolder = "Please enter your name"

    let formMessage = FormMessage(title: "Title",receiverUid: receiverId,receiverType: .user, formFields: [nameInput],submitElement: submitButton)

    CometChatUIKit.sendFormMessage(formMessage) { form in
      print("Form message sent: \(form)")
    } onError: { error in
      print("CometChat exception: \(error)")
    }
    ```
  </Tab>
</Tabs>

***

#### Card Message

To send a Card message to a single user or a group, use the `sendCardMessage()` function. This function requires a `CardMessage` object containing the necessary information to create a card bubble for the message.

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    let apiAction = APIAction()
    apiAction.url = "https://example.com/api"
    apiAction.method = .POST

    let cardAction = ButtonElement()
    cardAction.elementId = "1"
    cardAction.action = apiAction
    cardAction.buttonText = "Click Me"

    let cardMessage = CardMessage(url:"ImageURL", receiverUid:"receiverId", receiverType:.user, cardActions:[cardAction],text: "This is a card")

    CometChatUIKit.sendCardMessage(cardMessage) { success in
      print("Card message sent: \(success)")
    } onError: { error in
      print("CometChat exception: \(error)")
    }
    ```
  </Tab>
</Tabs>

***

#### Scheduler Message

To send a Scheduler message to a single user or a group, use the `sendSchedulerMessage()` function. This function requires a `SchedulerMessage` object containing the necessary information to create a scheduler bubble for the message.

<Tabs>
  <Tab title="Swift">
    ```swift lines theme={null}
    var interactiveData = [String: Any]()
    interactiveData["key"] = "value"

    let schedulerMessage = SchedulerMessage(receiverUid: "receiver_uid", type: "scheduler message type", receiverType: .user, interactiveData: interactiveData)

    CometChatUIKit.sendSchedulerMessage(schedulerMessage: schedulerMessage) { scheduler in
      print("Scheduler message sent: \(scheduler)")
    } onError: { error in
      print("CometChat exception: \(error)")
    }
    ```
  </Tab>
</Tabs>

***

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Events" icon="bolt" href="/ui-kit/ios/events">
    Listen to UI Kit component events
  </Card>

  <Card title="Getting Started" icon="rocket" href="/ui-kit/ios/getting-started">
    Set up the iOS UI Kit from scratch
  </Card>

  <Card title="Components Overview" icon="puzzle-piece" href="/ui-kit/ios/components-overview">
    Explore all available UI components
  </Card>

  <Card title="SDK Overview" icon="code" href="/sdk/ios/overview">
    Explore the underlying CometChat SDK
  </Card>
</CardGroup>
