Skip to main content
Version: v4

Methods

CometChatUIKit is a class that contains all necessary methods to help initialize the CometChat SDK with valid credentials for the ui kit to utilize.

The following properties and methods are present:

ParametersTypeDescription
authSettingsUIKitSettingsobject containing credentials to initialize CometChat SDK. This object must be populated first in order to initialize.
initpublic init(authSettings: UIKitSettings, result: @escaping (Result<Bool, Error>) -> Void)method initializes the settings required for CometChat SDK. First, ensure authSettings is set and then call the init() method on app startup
loginstatic public func login(uid: String, result: @escaping (LoginResult) -> Void)used for logging in with credentials but use this function only for testing purpose
loginWithAuthTokenstatic public func login(authToken: String, result: @escaping (LoginResult) -> Void)The CometChat SDK maintains the session of the logged in user within the SDK. Thus you do not need to call the login method for every session. You can use the CometChat.getLoggedInUser() method to check if there is any existing session in the SDK. This method should return the details of the logged-in user. \n\n\nCreate an Auth Token via the CometChat API for the new user every time the user logs in to your app
logoutstatic public func logout(user: User, result: @escaping (LoginResult) -> Void)used for ending user session of logged in user
createUserstatic public func create(user: User, result: @escaping (LoginResult) -> Void)used for creating new user
updateUserstatic public func update(user: User, result: @escaping (LoginResult) -> Void)used for updating user object
sendCustomMessagepublic static func sendCustomMessage(message: CustomMessage)can be used to send a custom message
sendTextMessagepublic static func sendTextMessage(message: TextMessage)can be used to send a text message
sendMediaMessagepublic static func sendMediaMessage(message: MediaMessage)can be used to send a media message

sendTextMessage

This method can be used to send text messages.

// first create a TextMessage object
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

// send the text message
CometChatUIKit.sendTextMessage(message: textMessage)

sendMediaMessage

This method can be used to send media messages.

// first create a MediaMessage object
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

// send the media message
CometChatUIKit.sendMediaMessage(message: MediaMessage)

sendCustomMessage

This method can be used to send custom messages.

// create a dictionary that will be passed to the CustomMessage object
var customData = [String: Any]()
customData["key"] = "value"

// first create a CustomMessage object
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()

// send the custom message
CometChatUIKit.sendCustomMessage(message: CustomMessage)

Send Form message

This method allows you to send Form messages which are the extension of Interactive Message.

// Create an instance of APIAction
let apiAction = APIAction()
apiAction.url = "https://example.com/api"
apiAction.method = .POST

// Create an instance of ButtonElement
let submitButton = ButtonElement()
submitButton.elementId = "1"
submitButton.action = apiAction
submitButton.buttonText = "Submit"

// Create an instance of TextInput
let nameInput = TextInput()
nameInput.elementId = "1"
nameInput.placeHolder = "Please enter your name"

// Create a new instance of FormMessage
let formMessage = FormMessage(title: "Title",receiverUid: receiverId,receiverType: .user, formFields: [nameInput],submitElement: submitButton);

CometChat.sendInteractiveMessage(message: interMessage, onSuccess: {
success in
print("succes"
}, onError: {
error in
print("errorr",error?.description
})

Send Card message

This method allows you to send Card messages which are the extension of Interactive Message

// Create instance of ButtonElement for card actions
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"
// Create a new instance of CardMessage
let cardMessage = CardMessage(url:"ImageURL", receiverUid:"receiverId", receiverType:.user, cardActions:[cardAction],text: "This is a card")

CometChat.sendInteractiveMessage(message: interMessage, onSuccess: {
success in
print("succes"
}, onError: {
error in
print("errorr",error?.description
})

UIKitSettings

UIKitSettings is an object containing credentials to initialize CometChat SDK.

PropertiesTypeDescription
set(appID: String)Stringthe unique ID for the app, available on dashboard
set(region: String)Stringthe region for the app us or eu
set(apiKey: String)Stringthe api key for the app, available on dashboard
set(authKey: String)Stringthe auth key for the app, available on dashboard
subscribePresenceForAllUsers()N.Asets user presence subscription for all users
subcribePresenceForRoles(roles: [String])[String]sets user presence subscription for specific roles
subscribePresenceForFriends()N.Asets user presence subscription for friends
autoEstablishSocketConnection(bool: Bool)Boolconfigure if web socket connections will established automatically on app initialization or be done manually, set to true by default
set(overrideAdminHost : String)Stringused to override the admin host
set(overrideClientHost : String)Stringused to override the client host

How to initialize the UI Kit?

The UI Kit can be initialized to use CometChatUIKit by populating the auth settings first and the calling the init method. Preferably this should be done at the top most level when the app starts.

info

Make sure you replace the APP_ID, REGION and AUTH_KEY with your CometChat App ID, Region and Auth Key in the below code. The Auth Key is an optional property of the UIKitSettings Class. It is intended for use primarily during proof-of-concept (POC) development or in the early stages of application development. You can use the Auth Token method to log in securely.

//CometChatUIKit should be initialized at the start of application. No need to initialize it again

import CometChatUIKitSwift
let uikitSettings = UIKitSettings()
uikitSettings.set(appID: <# Enter Your App ID Here #>)
.set(authKey: <# Enter Your AuthKey Here or leave blank If you are authenticating using Auth Token #>)
.set(region: <# Enter Your Region Code Here #> )
.subscribePresenceForAllUsers()
.build()
CometChatUIKit.init(uiKitSettings: uikitSettings, result: {
result in
switch result {
case .success(let success):
debugPrint("Initialization completed successfully \(success)")
break
case .failure(let error):
debugPrint( "Initialization failed with exception: \(error.localizedDescription)")
break
}
})

How to login a user of your App?

Only the UID of a user is needed to log in. This simple authentication procedure is useful when you are creating a POC or if you are in the development phase. For production apps, we suggest you use AuthToken instead of Auth Key.

let uid = <# Enter User's UID Here #>

CometChatUIKit.login(uid: uid) { result in
switch result {
case .success(let user):
debugPrint("User logged in successfully \(user.name)")
break
case .onError(let error):
debugPrint("Login failed with exception: \(error.errorDescription)")
break
}
}

How to login a user with Auth Token?

This advanced authentication procedure does not use the Auth Key directly in your client code thus ensuring safety.

  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: authToken) method.
let authToken = <# Enter User's AuthToken Here #>

CometChatUIKit.login(authToken: authToken) { result in
switch result {
case .success(let user):
debugPrint("User logged in successfully \(user.name)")
break
case .onError(let error):
debugPrint("Login failed with exception: \(error.errorDescription)")
break
}
}

How to create a new user for your App?

Create an object the new user that needs to created with as little information as the name of the user and a uid and pass it to the create(user: User) method

let uid = <# Enter User's UID Here #>
let name = <# Enter User Name Here #>
let avatar = <# Enter User's Avatar URL Here #>

let user = User(uid: uid, name: name)
user.avatar = avatar

CometChatUIKit.create(user: user) { result in
switch result {
case .success(let success):
debugPrint("User created successfully \\(user.name)")
break
case .onError(let error):
debugPrint("Creating new user failed with exception: \\(error.errorDescription)")
break
}
}

How to update a user for your App?

Update an object the user that needs to updated with as little information as the name of the user and a uid and pass it to the update(user: User) method

let uid = <# Enter User's UID Here #>
let name = <# Enter Updated User Name Here #>
let avatar = <# Enter Updated User's Avatar URL Here #>

let user = User(uid: uid, name: name)
user.avatar = avatar

CometChatUIKit.update(user: user) { result in
switch result {
case .success(let success):
debugPrint("User updated successfully \\(user.name)")
break
case .onError(let error):
debugPrint("Updating user failed with exception: \\(error.errorDescription)")
break
}
}

How to logout from a logged-In User in App?

just pass the loggedIn-user to the logout method

let uid = <# Enter User's UID Here #>
let name = <# Enter Updated User Name Here #>

let user = User(uid: uid, name: name)

CometChatUIKit.logout(user: user) { result in
switch result {
case .success(let success):
debugPrint("User logged-out successfully \\(user.name)")
break
case .onError(let error):
debugPrint("Logged-out user failed with exception: \\(error.errorDescription)")
break
}
}