CometChat Pro Documentation

You'll find comprehensive guides and documentation to help you start working with CometChat as quickly as possible. Let's jump right in!

Messaging

Send a Text Message

To send a text message to any particular user or group, you need to use the sendMessage() method.

let receiverID = "SUPERHERO2"
let text = "Hello"

let textMessage = TextMessage(receiverUid: receiverID, text: text, messageType: .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);
}
let receiverID = "SUPERGROUP02"
let text = "Hello"

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

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

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

}) { (error) in

  print("TextMessage sending failed with error: " + error.errorDescription);
}
NSString *receiverID = @"SUPERHERO01";
NSString *text       = @"Hello";

TextMessage *textMessage = [[TextMessage alloc]initWithReceiverUid:receiverID text:text messageType:MessageTypeText receiverType:ReceiverTypeUser];

[CometChat sendTextMessageWithMessage:textMessage onSuccess:^(TextMessage * message) {
    
    NSLog(@"TextMessage sent successfully. %@",[message stringValue]);
  
} onError:^(CometChatException * error) {
    
    NSLog(@"TextMessage sending failed with error: %@",[error errorDescription]);
}];
NSString *receiverID = @"SUPERGROUP01";
NSString *text       = @"Hello";

TextMessage *textMessage = [[TextMessage alloc]initWithReceiverUid:receiverID text:text messageType:MessageTypeText receiverType:ReceiverTypeGroup];

[CometChat sendTextMessageWithMessage:textMessage onSuccess:^(TextMessage * message) {
    
    NSLog(@"TextMessage sent successfully. %@",[message stringValue]);
  
} onError:^(CometChatException * error) {
    
    NSLog(@"TextMessage sending failed with error: %@",[error errorDescription]);
}];

To send a message you need to create an object of the TextMessage class. The initialize method of the TextMessage class takes the following mandatory parameters:

Parameters
Information

receiverID

The UID or GUID of the recipient

text

The text to be sent

messageType

The type of the message that needs to be sent, which in this case is text.

receiverType

The type of the receiver to whom the message is to be sent i.e user or group

Send Media Message

To send a media message to any user or group, you need to use the sendMediaMessage() method.

let receiverid = "SUPERHERO2"

let mediaUrl = "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);
}
let receiverid = "SUPERHERO2"

let mediaUrl = "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: .group);

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

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

}) { (error) in

  print("MediaMessage sending failed with error: " + error.errorDescription);
}
NSString *receiverID = @"SUPERHERO01";

NSString *filePath = @"Library/Developer/CoreSimulator/Devices/(numbers and letters)/data/Containers/Data/Application/(numbers and letters)/Documents/image.jpg";

MediaMessage *mediaMessage = [MediaMessage alloc]initWithReceiverUid:receiverID fileurl:filePath messageType:messageTypeImage receiverType:ReceiverTypeUser];

[CometChat sendMediaMessageWithMessage:mediaMessage onSuccess:^(MediaMessage * message) {
    
    NSLog(@"MediaMessage sent successfully. %@",[message stringValue]);
  
} onError:^(CometChatException * error) {
    
    NSLog(@"MediaMessage sending failed with error: %@",[error errorDescription]);
    
}];
NSString *receiverID = @"SUPERHERO01";

NSString *filePath = @"Library/Developer/CoreSimulator/Devices/(numbers and letters)/data/Containers/Data/Application/(numbers and letters)/Documents/image.jpg";

MediaMessage *mediaMessage = [MediaMessage alloc]initWithReceiverUid:receiverID fileurl:filePath messageType:messageTypeImage receiverType:ReceiverTypeGroup];

[CometChat sendMediaMessageWithMessage:mediaMessage onSuccess:^(MediaMessage * message) {
    
    NSLog(@"MediaMessage sent successfully. %@",[message stringValue]);
  
} onError:^(CometChatException * error) {
    
    NSLog(@"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:

Parameter
Description

receiverId

The UID or GUID of the recipient

fileurl

The file path object to be sent

messageType

The type of the message that needs to be sent which in this case can be:

  • image
  • video
  • audio
  • file

receiverType

The type of the receiver to whom the message is to be sent

  • user
  • group

On success, you will receive an object of the MediaMessage class containing all the information related to the sent media message.

Send 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.

Once the object of CustomMessage class is ready you can send the custom message using the sendCustomMessage() method.

let receiverid = "SUPERHERO2"

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);
}
let receiverid = "SUPERHERO2"

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

let customMessage = CustomMessage(receiverUid: receiverid, receiverType: .group, 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);
}
NSString *receiverID = @"SUPERHERO01";

NSMutableDictionary<NSString *, id> *customData = [NSMutableDictionary new];
    [customData setObject:@"customData" forKey:@"customKey"];

CustomMessage *customMessage = [CustomMessage alloc]initWithReceiverUid:receiverID receiverType:ReceiverTypeUser customData: customData type:@"Custom Type"];

[CometChat sendCustomMessageWithMessage:customMessage onSuccess:^(CustomMessage * message) {
    
    NSLog(@"CustomMessage sent successfully. %@",[message stringValue]);
  
} onError:^(CometChatException * error) {
    
    NSLog(@"CustomMessage sending failed with error: %@",[error errorDescription]);
    
}];
NSString *receiverID = @"SUPERHERO01";

NSMutableDictionary<NSString *, id> *customData = [NSMutableDictionary new];
[customData setObject:@"customData" forKey:@"customKey"];

CustomMessage *customMessage = [CustomMessage alloc]initWithReceiverUid:receiverID receiverType:ReceiverTypeGroup customData: customData type:@"Custom Type"];

[CometChat sendCustomMessageWithMessage:customMessage onSuccess:^(CustomMessage * message) {
    
    NSLog(@"CustomMessage sent successfully. %@",[message stringValue]);
  
} onError:^(CometChatException * error) {
    
    NSLog(@"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 containing all the information related to the sent custom message.

Send Custom Data along with a Message

To send custom data along with either a text or a media message, you can use the metadata field provided in both TextMessage, MediaMessage and CustomMessage class. 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 receiverID = "SUPERHERO01"
let text = "Hello"

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

let metadata = ["latitude":"50.6192171633316","longitude":"-72.68182268750002"];

textMessage.metaData = metadata;

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

  print("Message sent successfully: " + message.stringValue())

}) { (error) in

  print("Message sending failed with error: " + error.errorDescription);
}
NSString *receiverID = @"SUPERHERO01";
NSString *text       = @"Hello";

TextMessage *textMessage = [[TextMessage alloc]initWithReceiverUid:receiverID text:text messageType:messageTypeText receiverType:ReceiverTypeGroup];

NSDictionary * metadata = @{@"latitude":@"50.6192171633316",@"longitude":@"-72.68182268750002"};

[textMessage setMetaData:metadata];

[CometChat sendTextMessageWithMessage:textMessage onSuccess:^(TextMessage * message) {
    
  NSLog(@"%@",[messageSent stringValue]);    
    
} onError:^(CometChatException * error) {
    
  NSLog(@"%@",[error ErrorDescription]);
}];

Custom data can be sent similarly for MediaMessage and CustomMessage (as well as to group).

Receive Messages

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

Edit Message

In order to edit a message, you can use the editMessage() method. This method takes an object of the BaseMessage class. At the moment, you are only allowed to edit TextMessage and CustomMessage. Thus, the BaseMessage object must either be a Text or a Custom Message.

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

CometChat.edit(message: textMessage, onSuccess: { (baseMessage) in
                
   print("Message edited successfully. \(baseMessage)")
                
}) { (error) in
                
   print("Message edit failed with error: \(error.errorDescription)")
}

The object of the edited message will be returned in the onSucess() callback method of the delegate. The message object will contain the editedAt field set with the timestamp of the time the message was edited. This will help you identify if the message was edited while iterating through the list of messages. The editedBy field is also set to the UID of the user who edited the message.In order to receive real-time events for message being edited, you must add protocol conformance CometChatMessageDelegate as Shown Below :

extension ViewController: CometChatMessageDelegate {

		func onMessageEdited(message: BaseMessage) {
        
        print("received edited message successfully.")
    }
}

Delete Message

In case you have to delete a message, you can use the deleteMessage() method. This method takes the message ID of the message to be deleted.

CometChat.delete(messageId: 12345, onSuccess: { (baseMessage) in
                
   rint("message deleted successfully. \(baseMessage)")
                
}) { (error) in
                
   print("delete message failed with error: \(error.errorDescription)")
}

Once the message is deleted, In the onSuccess() callback, you get an object of the BaseMessage class, with the deletedAt field set with the timestamp of the time the message was deleted. Also, the deletedBy field is set. These two fields can be used to identify if the message is deleted while iterating through a list of messages.In order to receive real-time events for message being edited, you must add protocol conformance CometChatMessageDelegate as Shown Below :

extension ViewController: CometChatMessageDelegate {

		func onMessageDeleted(message: BaseMessage) {
        
        print("received deleted message successfully.")
    }
}

Also, while fetching the list of messages, if the message with ID of 100 was edited or deleted and the total number of messages in the conversation are 110, the 111st message fetched will be an Action message informing the user that the message with the ID 100 has been edited/deleted. To get the message object from the Action message object, you can use the action.actionOn property which can be cast to the BaseMessage object.

Important

In order to edit or delete a message you need to be either the sender of the message or the admin/moderator of the group in which the message was sent.

Fetch Messages

In order to fetch messages in bulk, the CometChat SDK provides the MessagesRequest class. To use this class i.e to create an object of the MessagesRequest class, you need to use the MessagesRequestBuilder class. The MessagesRequestBuilder class allows you to set the parameters based on which the messages are to be fetched.The MessagesRequestBuilder class allows you to set the below parameters:

  1. set(UID : String) - This method sets the UID of the user for which the messages are to be fetched i.e. The messages fetched will be a part of the conversation between the logged in user and the UID set using the setUID() method.
    let messagesRequest = MessagesRequest.MessageRequestBuilder()
    .set(UID: "Superhero")
    .build();
    
  2. set(GUID: String) - This method sets the GUID of the group for which the messages are to be fetched.
    let messagesRequest = MessagesRequest.MessageRequestBuilder()
    .set(GUID: "Supergroup")
    .build();
    
  3. set(messageID : Int) - This method sets the messageID before or after which the messages are to be fetched.
    let messagesRequest = MessagesRequest.MessageRequestBuilder()
    .set(GUID: "Supergroup")
    .set(messageId: 1010)
    .build();
    
  4. set(timestamp : Int) - This method sets the timestamp before or after which the messages are to be fetched.
    let messagesRequest = MessagesRequest.MessageRequestBuilder()
    .set(GUID: "Supergroup")
    .set(timestamp: 1559735981)
    .build();
    
  5. set(unread : Bool) - This method sets the unread parameter which determines if only the unread messages need to be fetched.
    let messagesRequest = MessagesRequest.MessageRequestBuilder()
    .set(GUID: "Supergroup")
    .set(unread : true)
    .build();
    
  6. set(undelivered : Bool) - This method sets the undelivered parameter which determines if only the undelivered messages need to be fetched.
    let messagesRequest = MessagesRequest.MessageRequestBuilder()
    .set(GUID: "Supergroup")
    .set(undelivered : true)
    .build();
    
  7. set(limit : Int) - This method sets the limit i.e. the number of messages that should be fetched in a single iteration.
    let messagesRequest = MessagesRequest.MessageRequestBuilder()
    .set(limit: 30)
    .build();
    
  8. hideMessagesFromBlockedUsers(Bool) - This parameter determines if the messages from blocked users are to be hidden in the list of messages fetched.
    let messagesRequest = MessagesRequest.MessageRequestBuilder()
    .set(GUID: "Supergroup")
    .set(undelivered : true)
    .hideMessagesFromBlockedUsers(true)
    .build();
    
  9. set(searchKeyword:String) - This parameter helps you get messages with the keyword specified. Once this parameter is set, the request will return messages containing the keyword.
    let messagesRequest = MessagesRequest.MessageRequestBuilder()
    .set(limit: 30)
    .set(searchKeyword : ''Hello'')
    .build();
    
    Finally, once all the parameters are set to the builder class, you need to call the build() method to get the object of the MessagesRequest class.
    let messagesRequest = MessagesRequest.MessageRequestBuilder()
    .set(limit: 30)
    .build();
    

The object of the MessagesRequest class can be used to call one of the two below methods:

  1. fetchPrevious() - this method fetches the messages prior to the parameters set.
  2. fetchNext() - this method fetches the messages after the parameters set.Calling the fetchPrevious() and fetchNext() on the same object of the MessagesRequest class, you can get the paginated list of messages till all the messages for the combination of the parameters set are fetched.Using the above set of methods, various combinations of messages can be fetched.

1. Fetch all messages

Using the same MessagesRequest class discussed above, you can fetch all the messages for a logged in user which involve his messages for all the User and Group conversations. Applying the filters using the MessagesRequestBuilder class, you can fetch messages either before or after a particular messageId or timestamp.The below code snippet shows how to fetch the latest 50 messages for the logged in user which include messages to and from the logged in user as a part of any User or Group conversations.

let limit = 50;

let messagesRequest = MessagesRequest.MessageRequestBuilder().set(limit: limit).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);
}
NSInteger limit = 50;

MessagesRequest *messageRequest = [[[[MessageRequestBuilder alloc]init] setWithLimit:limit] build];

[messageRequest fetchPreviousOnSuccess:^(NSArray<BaseMessage *> * messages) {

  for (BaseMessage *message in messages) {

      if ([message isKindOfClass:TextMessage.self]) {

          TextMessage *receivedMessage = (TextMessage *)message;
          NSLog(@"TextMessage received successfully. %@",[receivedMessage stringValue]);
      }
      else if ([messages isKindOfClass:MediaMessage.self]) {

          MediaMessage *receivedMessage = (MediaMessage *)message;
          NSLog(@"MediaMessage received successfully. %@",[receivedMessage stringValue]);
      }
  }

} onError:^(CometChatException * error) {

	NSLog(@"Message receiving failed with error: %@",[error ErrorDescription]);

}];

Calling the fetchPrevious() method on the same object repeatedly allows you to fetch all the previous messages in a paginated way.

2. Fetch Messages when User was offline.

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.Below code snippet demonstrates how this can be achieved.

let limit = 50;
let latestId = CometChat.getLastDeliveredMessageId()

let messagesRequest = MessagesRequest.MessageRequestBuilder().set(messageID: latestId).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);
}
NSInteger limit = 50;
NSString *latestMessageId = [CometChat getLatestDeliveredMessageId];

MessagesRequest *messageRequest = [[[[[MessageRequestBuilder alloc]init] setWithMessageID: latestMessageId] setWithLimit:limit] build];

[messageRequest fetchNextOnSuccess:^(NSArray<BaseMessage *> * messages) {

  for (BaseMessage *message in messages) {

      if ([message isKindOfClass:TextMessage.self]) {

          TextMessage *receivedMessage = (TextMessage *)message;
          NSLog(@"TextMessage received successfully. %@",[receivedMessage stringValue]);
      }
      else if ([messages isKindOfClass:MediaMessage.self]) {

          MediaMessage *receivedMessage = (MediaMessage *)message;
          NSLog(@"MediaMessage received successfully. %@",[receivedMessage stringValue]);
      }
  }

} onError:^(CometChatException * error) {

	NSLog(@"Message receiving failed with error: %@",[error ErrorDescription]);

}];

Using additional filters you can also fetch the offline messages for a particular User or a Group conversation too.Calling the fetchNext() method on the same object repeatedly allows you to fetch all the offline messages for the logged in user.

3. Fetch messages for a User 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. For this use case, it is mandatory to set the UID parameter using the set(UID:) method of the builder. This UID is the unique id of the user for which the conversation needs to be fetched.

let limit = 50;
let uid = "UID"
let messagesRequest = MessagesRequest.MessageRequestBuilder().set(UID: uid).set(limit: limit).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);
}
NSInteger limit = 50;
NSString *uid = "UID";

MessagesRequest *messageRequest = [[[[[MessageRequestBuilder alloc] init] setWithUID: uid] setWithLimit:limit] build];

[messageRequest fetchPreviousOnSuccess:^(NSArray<BaseMessage *> * messages) {

  for (BaseMessage *message in messages) {

      if ([message isKindOfClass:TextMessage.self]) {

          TextMessage *receivedMessage = (TextMessage *)message;
          NSLog(@"TextMessage received successfully. %@",[receivedMessage stringValue]);
      }
      else if ([messages isKindOfClass:MediaMessage.self]) {

          MediaMessage *receivedMessage = (MediaMessage *)message;
          NSLog(@"MediaMessage received successfully. %@",[receivedMessage stringValue]);
      }
  }

} onError:^(CometChatException * error) {

	NSLog(@"Message receiving failed with error: %@",[error ErrorDescription]);

}];

Calling the fetchPrevious() method on the same object repeatedly allows you to fetch the entire conversation between the logged in user and the specified user. This can be implemented with upward scrolling to display the entire conversation.

4. Fetch Messages for a Group 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 for any group provided you have joined the group. For this use case, it is mandatory to set the GUID parameter using the set(GUID:) method of the builder. This GUID is the unique identifier of the Group for which the messages are to be fetched.

let limit = 50;
let guid = "GUID"
let messagesRequest = MessagesRequest.MessageRequestBuilder().set(GUID: guid).set(limit: limit).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);
}
NSInteger limit = 50;
NSString *guid = "GUID";

MessagesRequest *messageRequest = [[[[[MessageRequestBuilder alloc] init] setWithGUID: guid] setWithLimit:limit] build];

[messageRequest fetchPreviousOnSuccess:^(NSArray<BaseMessage *> * messages) {

  for (BaseMessage *message in messages) {

      if ([message isKindOfClass:TextMessage.self]) {

          TextMessage *receivedMessage = (TextMessage *)message;
          NSLog(@"Text Message received successfully. %@",[receivedMessage stringValue]);
      }
      if ([messages isKindOfClass:MediaMessage.self]) {

          MediaMessage *receivedMessage = (MediaMessage *)message;
          NSLog(@"Media Message received successfully. %@",[receivedMessage stringValue]);
      }
  }

} onError:^(CometChatException * error) {

	NSLog(@"Message receiving failed with error: %@",[error ErrorDescription]);

}];

Calling the fetchPrevious() method on the same object repeatedly allows you to fetch the entire conversation for the group. This can be implemented with upward scrolling to display the entire conversation.

Get all unread messages.

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.

let messageRequest = MessageRequest.MessageRequestBuilder().set(unread:true).set(limit:20).build();

messageRequest.fetchPrevious(onSuccess : { (baseMessages) in

   print("successfully fetched unread messages \(baseMessages)")

}, onError : { (error) in

	 print("error while fetching unread messages: \(error.errorDescription)")
})
NSInteger limit = 50;

MessagesRequest *messageRequest = [[[[[MessageRequestBuilder alloc]init]  setWithUnread:YES] setWithLimit:limit] build];

[messageRequest fetchPreviousOnSuccess:^(NSArray<BaseMessage *> * messages) {

	NSLog(@"Unread messages receiving successful. %@",messages);
  
} onError:^(CometChatException * error) {

	NSLog(@"Unread messages receiving failed with error: %@",[error  ErrorDescription]);

}];

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 if let method to check the type of object.


What's Next

Calling

Messaging


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.