Quick Reference for AI Agents & Developers
Set delegate: CometChat.messagedelegate = self (conform to CometChatMessageDelegate)
Protocol: Implement CometChatMessageDelegate in your view controller
Delegate methods: onTextMessageReceived(_:), onMediaMessageReceived(_:), onCustomMessageReceived(_:)
Missed messages: Use MessagesRequest with setMessageId() to fetch messages received while offline
Related: Send Message · Typing Indicators · Messaging Overview
Receiving messages with CometChat has two parts:
Adding a listener to receive real-time messages when your app is running
Calling a method to retrieve missed messages when your app was not running
Object Structures
For complete object structure definitions, see Send Message - Object Structures :
Real-time Messages
In other words, as a recipient, how do I receive messages when my app is running?
In order to receive incoming messages, you must add protocol conformance CometChatMessageDelegate as Shown Below :
extension ViewController : CometChatMessageDelegate {
func onTextMessageReceived ( textMessage : TextMessage) {
print ( "TextMessage received successfully: " + textMessage. stringValue ())
}
func onMediaMessageReceived ( mediaMessage : MediaMessage) {
print ( "MediaMessage received successfully: " + mediaMessage. stringValue ())
}
func onCustomMessageReceived ( customMessage : CustomMessage) {
print ( "CustomMessage received successfully: " + customMessage. stringValue ())
}
}
@interface ViewController ()<CometChatMessageDelegate>
@end
@implementation ViewController
- ( void ) viewDidLoad {
[ super viewDidLoad ];
CometChat . messagedelegate = self ;
}
- ( void ) onTextMessageReceivedWithTextMessage: (TextMessage * ) textMessage {
NSLog ( @"TextMessage received successfully: %@ " ,[textMessage stringValue ]);
}
- ( void ) onMediaMessageReceivedWithMediaMessage: (MediaMessage * ) mediaMessage {
NSLog ( @"MediaMessage received successfully: %@ " ,[mediaMessage stringValue ]);
}
- ( void ) onCustomMessageReceivedWithCustomMessage: (CustomMessage * ) customMessage {
NSLog ( @"CustomMessage received : %@ " ,[customMessage stringValue ]);
}
@end
Do not forget to set your view controller as a CometChat delegate probably in viewDidLoad() as CometChat.messagedelegate = self
Sample Payloads - onTextMessageReceived
Request
Success Response
Error Response
Delegate Method: CometChatMessageDelegate.onTextMessageReceived(textMessage:)Parameter Type Value — — N/A - This is a delegate callback, not a request
The delegate method fires when a TextMessage is received in real-time. Object Type: TextMessage Parameter Type Value id Int37799muid String"1771917874.691467"conversationId String"cometchat-uid-2_user_cometchat-uid-3"senderUid String"cometchat-uid-3"receiverUid String"cometchat-uid-2"receiverType CometChat.ReceiverType0 (.user)messageType CometChat.MessageType0 (.text)messageCategory CometChat.MessageCategory0 (.message)sentAt Int1771917874deliveredAt Double0.0readAt Double0.0editedAt Double0.0deletedAt Double0.0updatedAt Double1771917874.0editedBy String""deletedBy String""parentMessageId Int0replyCount Int0unreadRepliesCount Int0metaData [String: Any][:] (empty dictionary)mentionedUsers [User][] (empty array)mentionedMe Boolfalsereactions [ReactionCount][] (empty array)text String"efefefwefefefewfef"
sender (User ):Parameter Type Value uid String"cometchat-uid-3"name String"Nancy Grace"avatar String"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"link String?nilrole String"moderator"status CometChat.UserStatus0 (.online)statusMessage String?nillastActiveAt Double1771586880.0hasBlockedMe BoolfalseblockedByMe Boolfalsemetadata [String: Any][:] (empty dictionary)deactivatedAt Double0.0
receiver (User ):Parameter Type Value uid String"cometchat-uid-2"name String"George Alan"avatar String"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"link String?nilrole String"moderator"status CometChat.UserStatus0 (.online)statusMessage String?nillastActiveAt Double1771917720.0hasBlockedMe BoolfalseblockedByMe Boolfalsemetadata [String: Any][:] (empty dictionary)deactivatedAt Double0.0
N/A — Delegate methods don’t return errors directly.Errors occur if SDK is not initialized or user not logged in.
Sample Payloads - onMediaMessageReceived
Sample Payloads - onCustomMessageReceived
Request
Success Response
Error Response
Delegate Method: CometChatMessageDelegate.onCustomMessageReceived(customMessage:)Parameter Type Value — — N/A - This is a delegate callback, not a request
The delegate method fires when a CustomMessage is received in real-time. Object Type: CustomMessage Parameter Type Value id Int37801muid String"1771918100.789012"conversationId String"cometchat-uid-2_user_cometchat-uid-3"senderUid String"cometchat-uid-3"receiverUid String"cometchat-uid-2"receiverType CometChat.ReceiverType0 (.user)messageType CometChat.MessageType0messageCategory CometChat.MessageCategory3 (.custom)sentAt Int1771918100deliveredAt Double0.0readAt Double0.0editedAt Double0.0deletedAt Double0.0updatedAt Double1771918100.0parentMessageId Int0replyCount Int0unreadRepliesCount Int0metaData [String: Any][:] (empty dictionary)mentionedUsers [User][] (empty array)mentionedMe Boolfalsereactions [ReactionCount][] (empty array)customType String"location"
customData ([String: Any]):Key Type Value latitude Double37.7749longitude Double-122.4194address String"San Francisco, CA"
sender (User ):Parameter Type Value uid String"cometchat-uid-3"name String"Nancy Grace"avatar String"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"role String"moderator"status CometChat.UserStatus0 (.online)
receiver (User ):Parameter Type Value uid String"cometchat-uid-2"name String"George Alan"avatar String"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"role String"moderator"status CometChat.UserStatus0 (.online)
N/A — Delegate methods don’t return errors directly.
As a sender, you will not receive your own message in a real-time message event. However, if a user is logged-in using multiple devices, they will receive an event for their own message in other devices.
Missed Messages
In other words, as a recipient, how do I receive messages that I missed when my app was not running?
For most cases, you will need to add functionality to load missed messages. If you’re building an on-demand or live streaming app, you may choose to skip this and fetch message history instead.
Using the same MessagesRequest class and the filters provided by the MessagesRequestBuilder class, you can fetch the message that we sent to the logged-in user but were not delivered to him as he was offline. For this, you will require the Id of the last message received. You can either maintain it at your end or use the getLastDeliveredMessageId() method provided by the CometChat class. This Id needs to be passed to the setMessageId() method of the builder class.
Now using the fetchNext() method, you can fetch all the messages that were sent to the user when he/she was offline.
Calling the fetchNext() method on the same object repeatedly allows you to fetch all the offline messages for the logged in user in a paginated manner
Fetch Missed Messages of a particular one-on-one conversation
let limit = 50 ;
let latestId = CometChat. getLastDeliveredMessageId ()
let UID = "cometchat-uid-2"
let messagesRequest = MessagesRequest. MessageRequestBuilder (). set ( messageID : latestId). set ( uid :UID). set ( limit : limit). build ();
messagesRequest. fetchNext ( onSuccess : { (messages) in
for message in messages ! {
if let receivedMessage = (message as? TextMessage) {
print ( "Message received successfully. " + receivedMessage. stringValue ())
}
else if let receivedMessage = (message as? MediaMessage) {
print ( "Message received successfully. " + receivedMessage. stringValue ())
}
}
}) { (error) in
print ( "Message receiving failed with error: " + error ! . errorDescription );
}
Sample Payloads - Fetch Missed Messages (User)
Request
Success Response
Error Response
Method: MessagesRequest.fetchNext()Parameter Type Value messageID Int37797 (last delivered message ID)uid String"cometchat-uid-2"limit Int50
Return Type: [BaseMessage] (Array of TextMessage , MediaMessage , or CustomMessage )Example TextMessage in array: Parameter Type Value id Int37798muid String"1771917734.123456"conversationId String"cometchat-uid-2_user_cometchat-uid-3"senderUid String"cometchat-uid-3"receiverUid String"cometchat-uid-2"receiverType CometChat.ReceiverType0 (.user)messageType CometChat.MessageType0 (.text)messageCategory CometChat.MessageCategory0 (.message)sentAt Int1771917734deliveredAt Double0.0readAt Double0.0text String"Hey, are you there?"
sender (User ):Parameter Type Value uid String"cometchat-uid-3"name String"Nancy Grace"avatar String"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"
receiver (User ):Parameter Type Value uid String"cometchat-uid-2"name String"George Alan"avatar String"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-2.webp"
Object Type: CometChatException Parameter Type Value errorCode String"ERROR_USER_NOT_LOGGED_IN"errorDescription String"Please log in to CometChat before calling this method"
Fetch Missed Messages of a particular group conversation
let limit = 50 ;
let latestId = CometChat. getLastDeliveredMessageId ()
let GUID = "cometchat-guid-1"
let messagesRequest = MessagesRequest. MessageRequestBuilder (). set ( messageID : latestId). set ( guid :GUID). set ( limit : limit). build ();
messagesRequest. fetchNext ( onSuccess : { (messages) in
for message in messages ! {
if let receivedMessage = (message as? TextMessage) {
print ( "Message received successfully. " + receivedMessage. stringValue ())
}
else if let receivedMessage = (message as? MediaMessage) {
print ( "Message received successfully. " + receivedMessage. stringValue ())
}
}
}) { (error) in
print ( "Message receiving failed with error: " + error ! . errorDescription );
}
Sample Payloads - Fetch Missed Messages (Group)
Request
Success Response
Error Response
Method: MessagesRequest.fetchNext()Parameter Type Value messageID Int37795 (last delivered message ID)guid String"cometchat-guid-1"limit Int50
Return Type: [BaseMessage]Example TextMessage in array: Parameter Type Value id Int37796muid String"1771917600.654321"conversationId String"group_cometchat-guid-1"senderUid String"cometchat-uid-3"receiverUid String"cometchat-guid-1"receiverType CometChat.ReceiverType1 (.group)messageType CometChat.MessageType0 (.text)messageCategory CometChat.MessageCategory0 (.message)sentAt Int1771917600text String"Hello team!"
sender (User ):Parameter Type Value uid String"cometchat-uid-3"name String"Nancy Grace"avatar String"https://assets.cometchat.io/sampleapp/v2/users/cometchat-uid-3.webp"
receiver (Group ):Parameter Type Value guid String"cometchat-guid-1"name String"Development Team"icon String"https://assets.cometchat.io/sampleapp/v2/groups/cometchat-guid-1.webp"type CometChat.GroupType"public"
Object Type: CometChatException Parameter Type Value errorCode String"ERROR_USER_NOT_LOGGED_IN"errorDescription String"Please log in to CometChat before calling this method"
Unread Messages
In other words, as a logged-in user, how do I fetch the messages I’ve not read?
Using the MessagesRequest class described above, you can fetch the unread messages for the logged-in user. In order to achieve this, you need to set the unread variable in the builder to true using the setUnread() method so that only the unread messages are fetched.
Fetch Unread Messages of a particular one-on-one conversation
let limit = 50 ;
let UID = "cometchat-uid-2"
let messagesRequest = MessagesRequest. MessageRequestBuilder (). set ( unread : true ). set ( limit : limit). set ( uid :UID). build ();
messagesRequest. fetchPrevious ( onSuccess : { (messages) in
for message in messages ! {
if let receivedMessage = (message as? TextMessage) {
print ( "Message received successfully. " + receivedMessage. stringValue ())
}
else if let receivedMessage = (message as? MediaMessage) {
print ( "Message received successfully. " + receivedMessage. stringValue ())
}
}
}) { (error) in
print ( "Message receiving failed with error: " + error ! . errorDescription );
}
Sample Payloads - Fetch Unread Messages (User)
Request
Success Response
Error Response
Method: MessagesRequest.fetchPrevious()Parameter Type Value uid String"cometchat-uid-2"unread Booltruelimit Int30
Return Type: [BaseMessage] (Array of unread messages)Example TextMessage in array: Parameter Type Value id Int37795muid String"1771917500.123456"conversationId String"cometchat-uid-2_user_cometchat-uid-3"senderUid String"cometchat-uid-3"receiverUid String"cometchat-uid-2"receiverType CometChat.ReceiverType0 (.user)messageType CometChat.MessageType0 (.text)sentAt Int1771917500deliveredAt Double0.0readAt Double0.0text String"Hey, are you there?"
Object Type: CometChatException Parameter Type Value errorCode String"ERROR_USER_NOT_LOGGED_IN"errorDescription String"Please log in to CometChat before calling this method"
Message History
In other words, as a logged-in user, how do I fetch the complete message history?
Fetch Message History of a particular one-on-one conversation
Using the MessagesRequest class and the filters for the MessagesRequestBuilder class as shown in the below code snippet, you can fetch the entire conversation between the logged in user and any particular user.
let limit = 50 ;
let UID = "cometchat-uid-2"
let messagesRequest = MessagesRequest. MessageRequestBuilder (). set ( limit : limit). set ( uid :UID). build ();
messagesRequest. fetchPrevious ( onSuccess : { (messages) in
for message in messages ! {
if let receivedMessage = (message as ? TextMessage) {
print ( "Message received successfully. " + receivedMessage. stringValue ())
}
else if let receivedMessage = (message as ? MediaMessage) {
print ( "Message received successfully. " + receivedMessage ! . stringValue ())
}
}
}) { (error) in
print ( "Message receiving failed with error: " + error ! . errorDescription );
}
Sample Payloads - Fetch Message History (User)
Request
Success Response
Error Response
Method: MessagesRequest.fetchPrevious()Parameter Type Value uid String"cometchat-uid-2"limit Int30
Return Type: [BaseMessage]Example TextMessage in array: Parameter Type Value id Int37790muid String"1771917000.111111"conversationId String"cometchat-uid-2_user_cometchat-uid-3"senderUid String"cometchat-uid-2"receiverUid String"cometchat-uid-3"receiverType CometChat.ReceiverType0 (.user)messageType CometChat.MessageType0 (.text)sentAt Int1771917000deliveredAt Double1771917005.0readAt Double1771917010.0text String"Hello!"
Object Type: CometChatException Parameter Type Value errorCode String"ERROR_USER_NOT_LOGGED_IN"errorDescription String"Please log in to CometChat before calling this method"
BaseMessage The list of messages received is in the form of objects of BaseMessage class. A BaseMessage can either be a TextMessage or a MediaMessage. You can use the instanceOf operator to check the type of object.
Common Error Codes
Error Code Description Resolution ERROR_USER_NOT_LOGGED_INUser is not logged in Call CometChat.login() first ERR_SDK_NOT_INITIALIZEDSDK not initialized Call CometChat.init() first ERR_NETWORK_ERRORNetwork connectivity issue Check internet connection and retry