Skip to main content

Retrieve Historical Messages

Retrieving historical messages can be done locally, remotely, or both locally and remotely.

Enable Service

Retrieving historical messages for one-to-one and group chats from the remote server refers to fetching historical messages from the RC server. This feature requires that the App Key has enabled the Cloud Storage for One-to-One and Group Messages service provided by RC. You can enable this service for the currently used App Key on the Chat pricing plans page in the Console. If using a production environment App Key, note that only the Chat Premium Plan or Chat Ultimate Plan can enable this service. Specific features and fees are subject to the Billing Explanation document.

Note: Please distinguish between historical message records and offline messages?. RC provides a default offline message cache service for one-to-one chats, group chats, and system messages for up to 7 days (adjustable). The SDK automatically retrieves messages during the offline period when the client goes online, and no API calls are required at the App layer. For details, see Manage Offline Message Storage Configuration.

Retrieve Messages from Local Database

Use the getHistoryMessages method to paginate and query historical messages stored in the local database for a specified conversation, returning a list of message objects. Messages in the list are sorted from newest to oldest by send time.

Retrieve All Types of Messages in a Conversation

Returns a list of RCMessage objects.

NSArray *history = [[RCIMClient sharedRCIMClient]
getHistoryMessages:ConversationType_PRIVATE
targetId:@"targetId"
oldestMessageId:lastMessageID
count:count];

The count parameter indicates how many messages should be included in the returned list. The oldestMessageId parameter controls the pagination boundary. Each time the getHistoryMessages method is called, the SDK will use the message pointed to by the oldestMessageId parameter as the boundary and continue to return the specified number of messages on the next page. If you need to retrieve the latest count messages in the conversation, set oldestMessageId to -1.

It is recommended to retrieve the ID of the earliest message in the returned result and pass it as oldestMessageId in the next call to traverse the entire conversation's message history.

ParameterTypeDescription
conversationType[RCConversationType]Conversation type
targetIdNSStringConversation ID
oldestMessageIdlongUse this messageId as the boundary to retrieve count messages with a smaller send time. Set to -1 if the ID does not exist, indicating to retrieve the latest count messages.
countintNumber of messages to retrieve, sorted by send time from newest to oldest

Retrieve Specified Types of Messages in a Conversation

Returns a list of RCMessage objects.

NSArray *history = [[RCIMClient sharedRCIMClient] getHistoryMessages:ConversationType_PRIVATE targetId:@"targetId" objectName:@"RC:TxtMsg" oldestMessageId:lastMessageID count:count];

The count parameter indicates how many messages should be included in the returned list. The oldestMessageId parameter controls the pagination boundary. Each time the getHistoryMessages method is called, the SDK will use the message pointed to by the oldestMessageId parameter as the boundary and continue to return the specified number of messages on the next page. If you need to retrieve the latest count messages in the conversation, set oldestMessageId to -1.

It is recommended to retrieve the ID of the earliest message in the returned result and pass it as oldestMessageId in the next call to traverse the entire conversation's message history.

ParameterTypeDescription
conversationType[RCConversationType]Conversation type
targetIdNSStringConversation ID
objectNameNSStringMessage type identifier. For built-in message type identifiers, see [Message Type Overview].
oldestMessageIdlongUse this messageId as the boundary to retrieve count messages with a smaller send time. Set to -1 if the ID does not exist, indicating to retrieve the latest count messages.
countintNumber of messages to retrieve, sorted by send time from newest to oldest

Retrieve Messages by Message UID

tip
  • SDK versions 5.2.5.1 and above support batch message retrieval by UID through an interface. This is only provided in the RCChannelClient class. Supported conversation types include one-to-one chat, group chat, chatroom, and ultra group.
  • If the SDK version is below 5.2.5.1, you can use the getMessageByUId method in the RCCoreClient class, which supports only one UID at a time.

The message UID is a globally unique ID generated by the RC server. After a message is stored in the local database, the App may need to extract specific messages again. For example, if your users wish to bookmark certain messages in the chat history, the App can first record the message UIDs and call getBatchLocalMessages when needed to display them, passing the bookmarked message UIDs to extract messages from the local database.

[[RCChannelClient sharedChannelManager] getBatchLocalMessages:conversationType_PRIVATE
targetId: @"targetId"
channelId: nil
messageUIDs:@[@"C3GC-8VAA-LJQ4-TPPM", @"B5GC-3VAA-LJQ4-TXXA"]]
success:^(NSArray<RCMessage *> *messages, NSArray<NSString *> *mismatch)) {}
error:^(RCErrorCode status) {};

As long as the message UIDs (messageUIDs) are held and the messages are already stored in the local database, this method can be used to extract messages from the local database. Only messages from one conversation (targetId) or ultra group channel (channelId) can be extracted at a time.

ParameterTypeDescription
conversationType[RCConversationType]Conversation type, supports one-to-one chat, group chat, chatroom, and ultra group.
targetIdNSStringConversation ID
channelIdNSStringUltra group channel ID. Pass null for non-ultra group conversation types.
messageUIDsNSArrayMessage UIDs, globally unique IDs generated by the RC server. Must provide valid UIDs, up to 20.
successBlockBlockSuccess callback. Returns a list of message objects and a list of UIDs that failed to be retrieved.
errorBlockBlockFailure callback.

For ultra group or chatroom conversation types, note the following:

  • Ultra group conversations by default only synchronize the last message of the conversation. If you directly call this method (e.g., you pass UIDs obtained through the RC server callback Post-messaging Callback), the SDK may not find the corresponding messages locally. It is recommended to first call getBatchRemoteUltraGroupMessages to retrieve messages from the server.
  • Chatroom conversations automatically clear local messages when the user exits. If the user exits the chatroom and then calls this interface, local messages cannot be retrieved.

Retrieve Remote Historical Messages

Use the getRemoteHistoryMessages method to directly query historical messages stored in the Cloud Storage for One-to-One and Group Messages for a specified conversation.

tip
  • Whether users can retrieve group chat historical messages sent before they joined the group depends on the App's settings in the Console. You can enable New Users Retrieve Historical Messages Before Joining Group on the [Basic Features] page in the Console. Enabling this option allows new group members to retrieve all group chat messages sent before they joined the group. If not enabled, new group members can only see group chat messages sent after they joined.
  • By default, users cannot retrieve historical messages from a group if they are not in the group. If you want users to be able to retrieve historical messages from a group even when they are not in the group, you can allow users not in the group to retrieve historical messages from the group through Configuration > Chat settings > Basic features > One-to-One and Group Chat > Can Users Retrieve Historical Messages When Not in Group in the RC Console.

Retrieve Remote Historical Messages for a Conversation

The SDK directly queries and retrieves historical messages that meet the query conditions from the Cloud Storage for One-to-One and Group Messages. The query results are compared with the local database, and duplicate messages are excluded before returning a list of message objects. Messages in the returned list are sorted from newest to oldest by send time.

Since this interface by default returns messages after deduplicating with local messages, it is recommended to first use getHistoryMessages, and after all local database messages are retrieved, then retrieve remote historical messages. Otherwise, some or all specified messages may not be retrieved.

[[RCIMClient sharedRCIMClient] getRemoteHistoryMessages:ConversationType_PRIVATE targetId:@"targetId" recordTime:recordTime count:count success:^(NSArray *messages, BOOL isRemaining) {

} error:^(RCErrorCode status) {

}];

The count parameter indicates how many messages should be included in the returned list. The recordTime parameter controls the pagination boundary. Each time the getRemoteHistoryMessages method is called, the SDK will use recordTime as the boundary and continue to return the specified number of messages on the next page. If you need to retrieve the latest count messages in the conversation, set recordTime to 0.

It is recommended to retrieve the sentTime of the earliest message in the returned result and pass it as recordTime in the next call to traverse the entire conversation's message history.

ParameterTypeDescription
conversationType[RCConversationType]Conversation type
targetIdNSStringConversation ID
recordTimelong longTimestamp, retrieves historical messages sent before recordTime. Pass 0 to retrieve the latest count messages. Default is 0.
countintNumber of messages to retrieve. If SDK < 5.4.1, range is [2-20]; if SDK ≧ 5.4.1, range is [2-100].
successBlockBlockSuccess callback
errorBlockBlockFailure callback
  • success details:

    Callback ParameterCallback TypeDescription
    messagesNSArrayRetrieved historical messages array
    isRemainingBOOLWhether there are remaining messages
  • error details:

    Callback ParameterCallback TypeDescription
    statusRCErrorCodeError code for failure

Customize Retrieval of Remote Historical Messages

Use RCRemoteHistoryMsgOption to customize the behavior of the getRemoteHistoryMessages method for retrieving remote historical messages. The SDK directly queries historical messages that meet the query conditions from the Cloud Storage for One-to-One and Group Messages.

RCRemoteHistoryMsgOption includes multiple configuration items, where count and recordTime parameters specify the number of historical messages to retrieve and the pagination query timestamp, respectively. The order parameter controls the time direction for retrieving historical messages, allowing you to choose to retrieve messages before or after the given recordTime. The includeLocalExistMessage parameter controls whether the returned message list should include messages already existing in the local database.

RCRemoteHistoryMsgOption *option = [RCRemoteHistoryMsgOption new];
option.recordTime = recordTime;
option.count = 10;
option.order = RCRemoteHistoryOrderDesc;
option.includeLocalExistMessage = NO;

[[RCIMClient sharedRCIMClient] getRemoteHistoryMessages:ConversationType_PRIVATE targetId:@"targetId" option:option success:^(NSArray *messages, BOOL isRemaining) {

} error:^(RCErrorCode status) {

}];

RCRemoteHistoryMsgOption defaults to querying messages in a conversation in descending order by send time and by default compares the query results with the local database, excluding duplicate messages before returning a list of message objects. When includeLocalExistMessage is set to NO, it is recommended that the App layer first use getHistoryMessages, and after all local database messages are retrieved, then retrieve remote historical messages, otherwise some or all specified messages may not be retrieved.

If you need to query messages in a conversation in ascending order by send time, it is recommended to retrieve the sentTime of the latest message in the returned result and pass it as recordTime in the next call to traverse the entire conversation's message history. Ascending order query is generally used for scenarios where you need to query updated historical messages after jumping to a specified message position in the conversation page.

ParameterTypeDescription
conversationType[RCConversationType]Conversation type
targetIdNSStringConversation ID
optionRCRemoteHistoryMsgOptionConfigurable parameters, including retrieval count, order, etc.
successBlockBlockSuccess callback
errorBlockBlockFailure callback
  • RCRemoteHistoryMsgOption details:

    ParameterDescription
    recordTimeTimestamp, used to control the boundary for paginated message queries. Default is 0.
    countNumber of messages to retrieve. If SDK < 5.4.1, range is [2-20]; if SDK ≧ 5.4.1, range is [2-100]; default is 0, indicating no retrieval.
    orderRetrieval order. RCRemoteHistoryOrderDesc: Descending, retrieves messages sent before recordTime in descending order by send time, returning messages in the list from newest to oldest. RCRemoteHistoryOrderAsc: Ascending, retrieves messages sent after recordTime in ascending order by send time, returning messages in the list from oldest to newest. Default is 1.
    includeLocalExistMessageWhether to include messages already existing in the local database. YES: Include, query results are returned directly without deduplicating with the local database. NO: Exclude, query results are first deduplicated with the local database, returning only messages not existing in the local database. Default is NO.
  • success details:

    Callback ParameterCallback TypeDescription
    messagesNSArrayRetrieved historical messages array
    isRemainingBOOLWhether there are remaining messages
  • error details:

    Callback ParameterCallback TypeDescription
    statusRCErrorCodeError code for failure

Retrieve Local and Remote Historical Messages

tip

This interface is provided in the RCCoreClient class. Note: Whether users can retrieve group chat historical messages sent before they joined the group depends on the App's settings in the Console. You can enable New Users Retrieve Historical Messages Before Joining Group on the [Basic Features] page in the Console. Enabling this option allows new group members to retrieve all group chat messages sent before they joined the group. If not enabled, new group members can only see group chat messages sent after they joined.

The getMessages method differs from getRemoteHistoryMessages in that getMessages first queries messages stored in the local database for the specified conversation, and when local messages cannot meet the query conditions, it then queries historical messages in the Cloud Storage for One-to-One and Group Messages, returning a continuous and adjacent list of message objects.

Use the RCHistoryMessageOption configuration in getMessages to customize the behavior of the getMessages method for retrieving remote historical messages.

RCHistoryMessageOption *option = [[RCHistoryMessageOption alloc] init];
option.order = RCHistoryMessageOrderDesc;
option.count = 20;
option.recordTime = message.sentTime; // If retrieving the latest 20 messages, pass 0.
[[RCCoreClient sharedCoreClient] getMessages:ConversationType_PRIVATE targetId:@"会话 id" option:option complete:^(NSArray *messages, RCErrorCode code) {
if (code == 0) {
// Success
} else {
// Failure
}
}];

RCHistoryMessageOption includes multiple configuration items. The count parameter indicates how many messages should be included in the returned list. The recordTime parameter controls the pagination boundary. Each time the `