Skip to main content
{
  "category": "methods",
  "wrapperClass": "CometChatUIKit",
  "methodCategories": [
    {
      "name": "initialization",
      "methods": [
        {"name": "init", "signature": "CometChatUIKit.init(uiKitSettings: UIKitSettings, completion:)", "description": "Initialize UI Kit with settings"}
      ]
    },
    {
      "name": "authentication",
      "methods": [
        {"name": "loginWithUID", "signature": "CometChatUIKit.login(uid: String, completion:)", "description": "Login using UID and Auth Key"},
        {"name": "loginWithToken", "signature": "CometChatUIKit.login(authToken: String, completion:)", "description": "Login using Auth Token"},
        {"name": "logout", "signature": "CometChatUIKit.logout(user: User, completion:)", "description": "Logout current user"},
        {"name": "createUser", "signature": "CometChatUIKit.create(user: User, completion:)", "description": "Create new user"}
      ]
    },
    {
      "name": "messaging",
      "methods": [
        {"name": "sendTextMessage", "signature": "CometChatUIKit.sendTextMessage(message: TextMessage)", "description": "Send text message"},
        {"name": "sendMediaMessage", "signature": "CometChatUIKit.sendMediaMessage(message: MediaMessage)", "description": "Send media message"},
        {"name": "sendCustomMessage", "signature": "CometChatUIKit.sendCustomMessage(message: CustomMessage)", "description": "Send custom message"}
      ]
    },
    {
      "name": "interactiveMessages",
      "methods": [
        {"name": "sendFormMessage", "signature": "CometChatUIKit.sendFormMessage(formMessage: FormMessage, completion:)", "description": "Send form message"},
        {"name": "sendCardMessage", "signature": "CometChatUIKit.sendCardMessage(cardMessage: CardMessage, completion:)", "description": "Send card message"},
        {"name": "sendSchedulerMessage", "signature": "CometChatUIKit.sendSchedulerMessage(schedulerMessage: SchedulerMessage, completion:)", "description": "Send scheduler message"}
      ]
    }
  ]
}

Overview

The UI Kit’s core function is to extend the CometChat SDK, 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 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.
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 instead.

UIKitSettings Properties

MethodTypeDescription
set(appID:)StringSets the unique ID for the app, available on dashboard
set(region:)StringSets the region for the app (‘us’ or ‘eu’)
set(authKey:)StringSets the auth key for the app, available on dashboard
subscribePresenceForAllUsersStringSets subscription type for tracking the presence of all users
subscribePresenceForFriendsStringSets subscription type for tracking the presence of friends
subscribePresenceForRolesStringSets subscription type for tracking the presence of users with specified roles
setAutoEstablishSocketConnectionBooleanConfigures if web socket connections will established automatically on app initialization or be done manually, set to true by default
setAIFeaturesList<AIExtensionDataSource>Sets the AI Features that need to be added in UI Kit
setExtensionsList<ExtensionsDataSource>Sets the list of extension that need to be added in UI Kit

Example

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)")
  }
}

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 instead.
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)")
  }
}

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 via the CometChat API when the user signs up in your app.
  2. Create an Auth Token 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.
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)")
  }
}

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.
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)")
  }
}

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.
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)")
  }
}

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.
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)
CometChatUIKit.sendTextMessage() automatically adds the message to the MessagesComponent and ConversationsComponent, handling all related cases for you. In contrast, CometChat.sendTextMessage() only sends the message without updating these UI Kit components.

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.
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)
CometChatUIKit.sendMediaMessage() automatically adds the message to the MessagesComponent and ConversationsComponent, handling all related cases for you. In contrast, CometChat.sendMediaMessage() only sends the message without updating these UI Kit components.

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.
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)
CometChatUIKit.sendCustomMessage() automatically adds the message to the MessagesComponent and ConversationsComponent, handling all related cases for you. In contrast, CometChat.sendCustomMessage() only sends the message without updating these UI Kit components.

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.
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)")
}

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.
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)")
}

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.
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)")
}