Skip to main content
Quick Reference for AI Agents & Developers
  • Text message: TextMessage(receiverUid:text:receiverType:)CometChat.sendTextMessage(message:onSuccess:onError:)
  • Media message: MediaMessage(receiverUid:fileurl:messageType:receiverType:)CometChat.sendMediaMessage(message:onSuccess:onError:)
  • Custom message: CustomMessage(receiverUid:receiverType:customData:type:)CometChat.sendCustomMessage(message:onSuccess:onError:)
  • Receiver types: .user, .group
  • Related: Receive Message · Interactive Messages · Messaging Overview
Using CometChat, you can send three types of messages:
  1. A text message, the most common and standard message type.
  2. A media message, for sending photos, videos and files.
  3. A custom message, for sending completely custom data using JSON structures.
  4. A Interactive Messages , for sending end-user interactive messages of type form, card and custom Interactive
You can also send metadata along with a text, media or custom message. Think, for example, if you’d want to share the user’s location with every message, you can use the metadata field.

Object Structures

TextMessage Object

The TextMessage object represents a text message in CometChat.
ParameterTypeDescription
idIntUnique message identifier assigned by CometChat
muidStringMessage unique identifier (client-generated)
conversationIdStringUnique conversation identifier
senderUidStringUID of the message sender
receiverUidStringUID/GUID of the message receiver
receiverTypeCometChat.ReceiverType.user (0) or .group (1)
messageTypeCometChat.MessageType.text (0) for text messages
messageCategoryCometChat.MessageCategory.message (0) for standard messages
sentAtIntUnix timestamp when message was sent
deliveredAtDoubleUnix timestamp when message was delivered
readAtDoubleUnix timestamp when message was read
editedAtDoubleUnix timestamp when message was edited
deletedAtDoubleUnix timestamp when message was deleted
updatedAtDoubleUnix timestamp of last update
editedByStringUID of user who edited the message
deletedByStringUID of user who deleted the message
parentMessageIdIntID of parent message (for threaded replies)
replyCountIntNumber of replies to this message
unreadRepliesCountIntNumber of unread replies
metaData[String: Any]Custom metadata dictionary
mentionedUsers[User]Array of mentioned users
mentionedMeBoolWhether current user is mentioned
reactions[ReactionCount]Array of reaction counts
textStringThe text content of the message
tags[String]Array of tags associated with the message
senderUserUser object of the sender
receiverUser or GroupUser or Group object of the receiver

MediaMessage Object

The MediaMessage object represents a media message (image, video, audio, file) in CometChat.
ParameterTypeDescription
idIntUnique message identifier assigned by CometChat
muidStringMessage unique identifier (client-generated)
conversationIdStringUnique conversation identifier
senderUidStringUID of the message sender
receiverUidStringUID/GUID of the message receiver
receiverTypeCometChat.ReceiverType.user (0) or .group (1)
messageTypeCometChat.MessageType.image (1), .video (2), .audio (3), .file (4)
messageCategoryCometChat.MessageCategory.message (0) for standard messages
sentAtIntUnix timestamp when message was sent
deliveredAtDoubleUnix timestamp when message was delivered
readAtDoubleUnix timestamp when message was read
editedAtDoubleUnix timestamp when message was edited
deletedAtDoubleUnix timestamp when message was deleted
updatedAtDoubleUnix timestamp of last update
parentMessageIdIntID of parent message (for threaded replies)
replyCountIntNumber of replies to this message
unreadRepliesCountIntNumber of unread replies
metaData[String: Any]Custom metadata dictionary
mentionedUsers[User]Array of mentioned users
mentionedMeBoolWhether current user is mentioned
reactions[ReactionCount]Array of reaction counts
attachmentAttachmentSingle attachment object
attachments[Attachment]?Array of attachments (for multiple files)
captionString?Caption text for the media
tags[String]Array of tags associated with the message
senderUserUser object of the sender
receiverUser or GroupUser or Group object of the receiver

CustomMessage Object

The CustomMessage object represents a custom message with arbitrary data.
ParameterTypeDescription
idIntUnique message identifier assigned by CometChat
muidStringMessage unique identifier (client-generated)
conversationIdStringUnique conversation identifier
senderUidStringUID of the message sender
receiverUidStringUID/GUID of the message receiver
receiverTypeCometChat.ReceiverType.user (0) or .group (1)
messageTypeCometChat.MessageTypeCustom type string
messageCategoryCometChat.MessageCategory.custom (3) for custom messages
sentAtIntUnix timestamp when message was sent
deliveredAtDoubleUnix timestamp when message was delivered
readAtDoubleUnix timestamp when message was read
editedAtDoubleUnix timestamp when message was edited
deletedAtDoubleUnix timestamp when message was deleted
updatedAtDoubleUnix timestamp of last update
parentMessageIdIntID of parent message (for threaded replies)
replyCountIntNumber of replies to this message
unreadRepliesCountIntNumber of unread replies
metaData[String: Any]Custom metadata dictionary
mentionedUsers[User]Array of mentioned users
mentionedMeBoolWhether current user is mentioned
reactions[ReactionCount]Array of reaction counts
customTypeStringCustom type identifier (e.g., “location”, “poll”)
customData[String: Any]Custom data dictionary
subTypeString?Optional sub-type for further categorization
updateConversationBoolWhether to update conversation’s last message
conversationTextString?Custom text for conversation preview/notifications
tags[String]Array of tags associated with the message
senderUserUser object of the sender
receiverUser or GroupUser or Group object of the receiver

User Object

The User object represents a CometChat user.
ParameterTypeDescription
uidStringUnique user identifier
nameStringDisplay name of the user
avatarString?Avatar image URL
linkString?Profile link URL
roleStringUser role (e.g., “default”, “moderator”, “admin”)
statusCometChat.UserStatus.online (0) or .offline (1)
statusMessageString?Custom status message
lastActiveAtDoubleUnix timestamp of last activity
hasBlockedMeBoolWhether this user has blocked the logged-in user
blockedByMeBoolWhether the logged-in user has blocked this user
metadata[String: Any]Custom metadata dictionary
deactivatedAtDoubleUnix timestamp when user was deactivated (0 if active)
tags[String]Array of tags associated with the user

Group Object

The Group object represents a CometChat group.
ParameterTypeDescription
guidStringUnique group identifier
nameStringDisplay name of the group
iconString?Group icon image URL
descriptionString?Group description
typeCometChat.GroupType.public, .private, or .password
ownerStringUID of the group owner
membersCountIntNumber of members in the group
createdAtDoubleUnix timestamp when group was created
updatedAtDoubleUnix timestamp of last update
hasJoinedBoolWhether the logged-in user has joined the group
joinedAtDoubleUnix timestamp when user joined the group
scopeCometChat.GroupMemberScope.participant, .moderator, or .admin
metadata[String: Any]?Custom metadata dictionary
tags[String]?Array of tags associated with the group

Attachment Object

The Attachment object represents a file attachment in a media message.
ParameterTypeDescription
fileNameStringName of the file
fileExtensionStringFile extension (e.g., “jpg”, “pdf”)
fileSizeIntFile size in bytes
fileMimeTypeStringMIME type (e.g., “image/jpeg”, “application/pdf”)
fileUrlStringURL to access the file

CometChatException Object

The CometChatException object represents an error returned by the SDK.
ParameterTypeDescription
errorCodeStringUnique error code identifier
errorDescriptionStringHuman-readable error message
detailsString?Additional context or troubleshooting information

Text Message

In other words, as a sender, how do I send a text message? To send a text message to a single user or group, you need to use the sendMessage() method and pass a TextMessage object to it.

Add Metadata

To send custom data along with a text message, you can use the metadata field provided in TextMessage. A metadata field is a dictionary of type [String: Any] which will be received as it was sent without any processing from CometChat. It can be used to send any additional data that needs to be sent along with a message.
let metadata = ["latitude":"50.6192171633316","longitude":"-72.68182268750002"];

textMessage.metaData = metadata;

Add Tags

To add a tag to a message you can use Array of strings that you need to set it to property tags.
let tags = ["pinned"]

textMessage.tags = tags;
Once the text message object is ready, you need to use the sendMessage() method to send the text message to the recipient.
let receiverID = "cometchat-uid-2"
let text = "Hello"

let textMessage = TextMessage(receiverUid: receiverID, text: text, receiverType: .user)

CometChat.sendTextMessage(message: textMessage, onSuccess: { (message) in

  print("TextMessage sent successfully. " + message.stringValue())

}) { (error) in

  print("TextMessage sending failed with error: " + error!.errorDescription);
}
The TextMessage class constructor takes the following parameters:
ParametersInformation
receiverIDThe UID or GUID of the recipient
textThe text to be sent
receiverTypeThe type of the receiver to whom the message is to be sent i.e user or group
The login() method returns the TextMessage object containing all the information of the sent message.
Method: CometChat.sendTextMessage(message:)Object Type: TextMessage (before sending)
ParameterTypeValue
idInt0
muidString""
conversationIdString""
senderUidString""
receiverUidString"cometchat-uid-3"
receiverTypeCometChat.ReceiverType0 (.user)
messageTypeCometChat.MessageType0 (.text)
messageCategoryCometChat.MessageCategory0 (.message)
sentAtInt0
deliveredAtDouble0.0
readAtDouble0.0
editedAtDouble0.0
deletedAtDouble0.0
updatedAtDouble0.0
editedByString""
deletedByString""
parentMessageIdInt0
replyCountInt0
unreadRepliesCountInt0
metaData[String: Any][:] (empty dictionary)
mentionedUsers[User][] (empty array)
mentionedMeBoolfalse
reactions[ReactionCount][] (empty array)
textString"Hello"
senderUser?nil
receiverUser?nil
Object Type: TextMessage
ParameterTypeValue
idInt143
muidString"1708934500456_user_12345"
senderUidString"user_12345"
receiverUidString"group_dev_team"
textString"Team meeting at 3 PM"
messageTypeCometChat.MessageType0 (.text)
receiverTypeCometChat.ReceiverType1 (.group)
messageCategoryCometChat.MessageCategory0 (.message)
sentAtInt1708934500
deliveredAtDouble?nil
readAtDouble?nil
editedAtDouble?nil
deletedAtDouble?nil
editedByString?nil
deletedByString?nil
conversationIdString"group_group_dev_team"
metaData[String: Any]?nil
tags[String]?nil
parentMessageIdInt0
replyCountInt0
unreadRepliesCountInt0
mentionedUsers[User][] (empty array)
mentionedMeBoolfalse
reactions[ReactionCount][] (empty array)
quotedMessageIdInt0
quotedMessageBaseMessage?nil
sender (User):
ParameterTypeValue
uidString"user_12345"
nameString"John Doe"
avatarString"https://data-us.cometchat.io/avatars/user_12345.png"
linkString?nil
roleString"default"
statusCometChat.UserStatus0 (.online)
statusMessageString?nil
lastActiveAtDouble1708934500.0
metadata[String: Any]?nil
tags[String]?nil
hasBlockedMeBoolfalse
blockedByMeBoolfalse
receiver (Group):
ParameterTypeValue
guidString"group_dev_team"
nameString"Development Team"
iconString"https://data-us.cometchat.io/groups/dev_team.png"
descriptionString"Team for development discussions"
typeCometChat.GroupType"public"
ownerString"user_admin"
membersCountInt15
createdAtDouble1700000000.0
updatedAtDouble1708900000.0
hasJoinedBooltrue
joinedAtDouble1705000000.0
scopeCometChat.GroupMemberScope"participant"
metadata[String: Any]?nil
tags[String]?nil

Set Quoted Message

To set a quoted message for a message, use the quotedMessageId.
textMessage.quotedMessageId = 0
textMessage.quotedMessage =  // Pass base message object here that you want to quote.
Once the text message object is ready, you need to use the sendMessage() method to send the text message to the recipient.
var textMessage = TextMessage(receiverUid: currentUser?.uid ?? "", text: message, receiverType: .user)
textMessage.quotedMessageId = swipedMessage.id

CometChat.sendTextMessage(message: textMessage, onSuccess: { (message) in
    print("success")
}) { (error) in
    DispatchQueue.main.async {
        if let error = error {
            print(error.errorDescription)
        }
    }
}
The TextMessage class constructor takes the following parameters:
ParameterDescription
receiverIDUID of the user or GUID of the group receiving the messageRequired
messageTextThe text messageRequired
receiverTypeThe type of the receiver- CometChatConstants.RECEIVER_TYPE_USER (user) or CometChatConstants.RECEIVER_TYPE_GROUP (group)Required
When a text message is sent successfully, the response will include a TextMessage object which includes all information related to the sent message.
Method: CometChat.sendTextMessage(message:)
ParameterTypeValue
receiverUidString"cometchat-uid-2"
textString"I agree with this!"
receiverTypeCometChat.ReceiverType0 (.user)
quotedMessageIdInt140

Media Message

In other words, as a sender, how do I send a media message like photos, videos & files? To send a media message to any user or group, you need to use the sendMediaMessage() method and pass a MediaMessage object to it.

Add Metadata

To send custom data along with a media message, you can use the metadata field provided in MediaMessage. A metadata field is a dictionary of type [String: Any] which will be received as it was sent without any processing from CometChat. It can be used to send any additional data that needs to be sent along with a message.
let metadata = ["latitude":"50.6192171633316","longitude":"-72.68182268750002"];

mediaMessage.metaData = metadata;

Add Caption(Text along with Media Message)

To send a caption with a media message, you can use setCaption method and pass text to it.
mediaMessage.caption = "Message Caption"

Add Tags

To add a tag to a message you can use Array of strings that you need to set it to property tags.
let tags = ["pinned"]

textMessage.tags = tags;
There are 2 ways you can send Media Messages using the CometChat SDK:
  1. By providing the File : You can directly share the file object while creating an object of the MediaMessage class. When the media message is sent using the sendMediaMessage() method, this file is then uploaded to CometChat servers and the URL of the file is sent in the success response of the sendMediaMessage() function.
let receiverid = "cometchat-uid-2"

let mediaUrl = "file:___Library_Developer_CoreSimulator_Devices_(numbers and letters)_data_Containers_Data_Application_(numbers and letters)_Documents_image.jpg"

let mediaMessage = MediaMessage(receiverUid: receiverid, fileurl:mediaUrl, messageType: .image, receiverType: .user);

CometChat.sendMediaMessage(message: mediaMessage, onSuccess: { (message) in

  print("MediaMessage sent successfully. " + message.stringValue())

}) { (error) in

  print("MediaMessage sending failed with error: " + error.errorDescription);
}
To send a media message you need to create an object of the MediaMessage class. The initialize method of the MediaMessage class takes the following mandatory parameters:
ParameterDescription
receiverIdThe UID or GUID of the recipientRequired
fileurlThe file path object to be sentRequired
messageTypeThe type of the message that needs to be sent which in this case can be: - image - video - audio - fileRequired
receiverTypeThe type of the receiver to whom the message is to be sent - user - groupRequired
  1. By providing the URL of the File: The second way to send media messages using the CometChat SDK is to provide the SDK with the URL of any file that is hosted on your servers or any cloud storage. To achieve this you will have to make use of the Attachment class that is available in the MediaMessage class. For more information, you can refer to the below code snippet:
let receiverid = "cometchat-uid-2"

let mediaUrl = "https:__pngimg.com_uploads_mario_mario_PNG125.png"

let mediaMessage = MediaMessage(receiverUid: receiverid, fileurl:"", messageType: .image, receiverType: .user);

mediaMessage.attachment = Attachment(fileName: "FileName", fileExtension: "png", fileMimeType: "image_png", fileUrl: mediaUrl);

CometChat.sendMediaMessage(message: mediaMessage, onSuccess: { (message) in

  print("MediaMessage sent successfully. " + message.stringValue())

}) { (error) in

  print("MediaMessage sending failed with error: " + error.errorDescription);
}
On success, you will receive an object of the MediaMessage class containing all the information related to the sent media message.
Method: CometChat.sendMediaMessage(message:)
ParameterTypeValue
receiverUidString"cometchat-uid-2"
messageTypeCometChat.MessageType1 (.image)
receiverTypeCometChat.ReceiverType0 (.user)
fileUrlString"file:///Library/Developer/CoreSimulator/.../image.jpg"
Object Type: MediaMessage
ParameterTypeValue
idInt148
muidString"1708937000123_user_12345"
senderUidString"user_12345"
receiverUidString"group_dev_team"
messageTypeCometChat.MessageType1 (.image)
receiverTypeCometChat.ReceiverType1 (.group)
messageCategoryCometChat.MessageCategory0 (.message)
sentAtInt1708937000
conversationIdString"group_group_dev_team"
captionString?nil
parentMessageIdInt0
replyCountInt0
attachment (Attachment):
ParameterTypeValue
fileNameString"team_photo.png"
fileExtensionString"png"
fileSizeInt512000
fileMimeTypeString"image/png"
fileUrlString"https://data-us.cometchat.io/assets/images/team_photo.png"
receiver (Group):
ParameterTypeValue
guidString"group_dev_team"
nameString"Development Team"
iconString"https://data-us.cometchat.io/groups/dev_team.png"
descriptionString"Team for development discussions"
typeCometChat.GroupType"public"
ownerString"user_admin"
membersCountInt15
If you wish to send a caption or some text along with the Media Message, you can use the caption field provided by the MediaMessage class. To set the caption you can use the setCaption() method and at the receiver end, you can obtain the caption using the getCaption() method. As with text messages, the metadata field can be used with media messages as well. Any additional information can be passed along with the media message as a JSONObject.

Multiple Attachments in a Media Message

Starting version 3.0.906 & above the SDK supports sending of multiple attachments in a single media message. As in case for single attachment in a media message, there are two ways you can send Media Messages using the CometChat SDK:
  1. By providing an array of files: You can now share a List of files while creating an object of the MediaMessage class. When the media message is sent using the sendMediaMessage() method, the files are uploaded to the CometChat servers & the URL of the files are sent in the success response of the sendMediaMessage() method.
String receiverId = "cometchat-uid-1"

let data = try? Data(contentsOf: URL(string: " file:___private_var_mobile_Containers_Data_Application_B71B0A14_tmp_1111.jpeg")
let data1 = try? Data(contentsOf: URL(string: " file:___private_var_mobile_Containers_Data_Application_B71B0A14_tmp_2222.jpeg")
let data2 = try? Data(contentsOf: URL(string: " file:___private_var_mobile_Containers_Data_Application_B71B0A14_tmp_3333.jpeg")

var files = [File]()
files.append(File(name: "FileName 1", data: data)
files.append(File(name: "FileName 2", data: data1)
files.append(File(name: "FileName 3", data: data2)

mediaMessage = MediaMessage(receiverUid: self.currentUser?.uid ?? "", files: files, messageType: .file, receiverType: .user)

CometChat.sendMediaMessage(message: mediaMessage, onSuccess: { (message) in
	print("Message sent successfully")
}, onError: { (error) in
  print("Message sending failed with exception : ", error?.errorDescription)
}
Method: CometChat.sendMediaMessage(message:)
ParameterTypeValue
receiverUidString"cometchat-uid-2"
messageTypeCometChat.MessageType4 (.file)
receiverTypeCometChat.ReceiverType0 (.user)
files ([File]):
Indexnamedata
0"FileName 1"<binary_data>
1"FileName 2"<binary_data>
2"FileName 3"<binary_data>

Custom Message

CometChat SDK allows you to send a completely custom message across. You can use this feature to send messages that do not fit in any default categories provided. In order to send a custom message, you need to use the sendCustomMessage() method. The sendCustomMessage() methods takes an object of the CustomMessage which can be obtained using the below two constructor:
let customMessage : CustomMessage = CustomMessage(receiverId: receiverId, receiverType: .user, customData : customData, type: "Custom Type")
The above constructor, helps you create a custom message with the message type set to whatever is passed to the constructor and the category set to custom. The parameters involved are:
  1. receiverId - Unique id of the user or group to which the message is to be sent.
  2. receiverType - Type of the receiver i.e user or group
  3. type - custom message type that you need to set
  4. customData - The data to be passed as the message in the form of a Dictionary object.
You can also use the subType field of the CustomMessage class to set a specific type for the CustomeMessage.

Add Tags

To add a tag to a message you can use Array of strings that you need to set it to property tags.
let tags = ["pinned"]

textMessage.tags = tags;
Once the object of CustomMessage class is ready you can send the custom message using the sendCustomMessage() method.
let receiverid = "cometchat-uid-2"

let customData : [String : Any] = ["customKey" : "customData"]

let customMessage = CustomMessage(receiverUid: receiverid, receiverType: .user, customData : customData, type: "Custom Type");

CometChat.sendCustomMessage(message: customMessage, onSuccess: { (message) in

  print("CustomMessage sent successfully. " + message.stringValue())

}) { (error) in

  print("CustomMessage sending failed with error: " + error!.errorDescription);
}
The above sample explains how custom messages can be used to share the location with a user. The same can be achieved for groups. In success, you will receive an object of the CustomMessage class.
Method: CometChat.sendCustomMessage(message:)
ParameterTypeValue
receiverUidString"cometchat-uid-2"
receiverTypeCometChat.ReceiverType0 (.user)
typeString"Custom Type"
customData ([String: Any]):
KeyTypeValue
customKeyString"customData"
Object Type: CustomMessage
ParameterTypeValue
idInt209
muidString"1708944500123_user_12345"
senderUidString"user_12345"
receiverUidString"user_67890"
customTypeString"location"
subTypeString?nil
receiverTypeCometChat.ReceiverType0 (.user)
messageCategoryCometChat.MessageCategory3 (.custom)
sentAtInt1708944500
conversationIdString"user_12345_user_user_67890"
updateConversationBooltrue
conversationTextString"📍 Shared a location"
customData ([String: Any]):
KeyTypeValue
latitudeString"37.7749"
longitudeString"-122.4194"
addressString"San Francisco, CA"
accuracyDouble10.5

Update Conversation

How can I decide whether the custom message should update last message of a conversation? By default, a custom message will update the last message of a conversation. If you wish to not update last message of conversation when a custom message is sent, please use updateConversation property of the Custom Message.
let receiverid = "cometchat-uid-2"
let customData : [String : Any] = ["customKey" : "customData"]
let customMessage = CustomMessage(receiverUid: receiverid, receiverType: .user, customData : customData, type: "Custom Type");

customMessage.updateConversation = false //for not updating conversation

CometChat.sendCustomMessage(message: customMessage, onSuccess: { (message) in
  print("CustomMessage sent successfully. " + message.stringValue())
}) { (error) in
  print("CustomMessage sending failed with error: " + error!.errorDescription);
}

Custom Notification Body

How can i customise the notification body of custom message? To add a custom notification body for Push, Email & SMS notification of a custom message you can use the conversationText property of Custom Message class.
let receiverid = "cometchat-uid-2"
let customData : [String : Any] = ["customKey" : "customData"]
let customMessage = CustomMessage(receiverUid: receiverid, receiverType: .user, customData : customData, type: "Custom Type");

customMessage.conversationText = "Custom notification body";

CometChat.sendCustomMessage(message: customMessage, onSuccess: { (message) in
  print("CustomMessage sent successfully. " + message.stringValue())
}) { (error) in
  print("CustomMessage sending failed with error: " + error!.errorDescription);
}
It is also possible to send interactive messages from CometChat , to know more click here

Common Error Codes

Error CodeDescriptionResolution
ERR_NOT_LOGGED_INUser is not logged inCall CometChat.login() first
ERR_FILE_SIZE_EXCEEDEDFile size exceeds maximum limitReduce file size to under 100MB
ERR_INVALID_RECEIVERInvalid receiver UID/GUIDVerify the receiver exists
ERR_BLOCKED_BY_USERBlocked by the receiverCannot send messages to users who blocked you
ERR_SDK_NOT_INITIALIZEDSDK not initializedCall CometChat.init() first
ERR_NETWORK_ERRORNetwork connectivity issueCheck internet connection and retry