Retrieve Historical Messages
When retrieving historical messages, you can choose to fetch them from local storage only, from the remote server only, or simultaneously from both local and remote sources. Ultra group conversations do not have offline messages. To retrieve messages received while the user was offline, you need to fetch remote historical messages based on the last message in the ultra group conversation.
- If your application/environment enabled ultra group services on or after October 13, 2022, the ultra group service includes a default channel with ID
RCDefault. If no channel ID is specified when sending messages, they will be sent to theRCDefaultchannel. When retrieving historical messages for theRCDefaultchannel, you must pass this channel ID. - If your application/environment enabled ultra group services before October 13, 2022, messages sent without specifying a channel ID will not belong to any channel. When retrieving historical messages without passing a channel ID, you can obtain messages that don't belong to any channel. RC supports adjusting services to the latest behavior. This adjustment will affect multiple functions including client/server message sending/receiving, conversation retrieval, message history clearing, and muting. If needed, please submit a ticket for detailed solutions.
- The Cloud Storage for One-to-One and Group Messages service is enabled by default. You can retrieve one-to-one and group chat historical messages from the remote server directly. For production environment App Keys, this service is available for Chat Starter Plan and Chat Pro Plan. Specific features and pricing are subject to the RC Official Pricing Page.
Retrieve Local and Remote Historical Messages
You can use the [getMessages] method to first retrieve historical messages from local storage, and synchronize missing portions from the server if local data is incomplete. When no more messages are available locally, they will be fetched from the server.
Method Prototype
- (void)getMessages:(RCConversationType)conversationType
targetId:(NSString *)targetId
channelId:(NSString *)channelId
option:(RCHistoryMessageOption *)option
complete:(void (^)(NSArray *messages,long long timestamp,BOOL isRemaining, RCErrorCode code))complete
error:(void (^)(RCErrorCode status))errorBlock;
Parameter Description
| Parameter | Type | Description |
|---|---|---|
| conversationType | [RCConversationType] | Conversation type |
| targetId | NSString | Conversation ID |
| channelId | NSString | Ultra group channel ID |
| option | RCHistoryMessageOption | Configurable parameters including fetch count and order |
| complete | Block | Message retrieval callback |
| error | Block | Message retrieval failure callback |
-
RCHistoryMessageOptionDetails:Parameter Description recordTime Timestamp for controlling pagination boundaries. Default: 0.count Number of messages to retrieve. For SDK < 5.4.1: range [2-20]; for SDK ≧ 5.4.1: range [2-100]; default: 0(no retrieval).order Retrieval order. RCHistoryMessageOrderDesc: Descending - retrieves messages sent beforerecordTimein reverse chronological order (newest to oldest).RCHistoryMessageOrderAsc: Ascending - retrieves messages sent afterrecordTimein chronological order (oldest to newest). Default: descending.
Sample Code
RCHistoryMessageOption *option = [[RCHistoryMessageOption alloc] init];
option.order = RCHistoryMessageOrderDesc;
option.count = 20;
option.recordTime = message.sentTime; // Pass 0 to retrieve the latest 20 messages
[[RCChannelClient sharedChannelManager] getMessages:ConversationType_ULTRAGROUP targetId:@"targetId" channelId:@"channelId" option:option complete:^(NSArray *messages, RCErrorCode code) {
if (code == 0) {
// Success
} else {
// Failure
}
}];
Retrieve Messages from Local Database
You can use the getHistoryMessages method to paginate through historical messages stored in the local database for a specified conversation, asynchronously returning a list of message objects sorted from newest to oldest by send time.
Retrieve Messages Before a Specified messageId in Ultra Groups
Asynchronously retrieves a specified number of message entities (RCMessage objects) that were sent before a specified message in the conversation.
Method Prototype
- (void)getHistoryMessages:(RCConversationType)conversationType
targetId:(NSString *)targetId
channelId:(nullable NSString *)channelId
oldestMessageId:(long)oldestMessageId
count:(int)count
completion:(nullable void(^)(NSArray<RCMessage *> * _Nullable messages))completion;
Parameter Description
The count parameter specifies how many messages should be included in the returned list. The oldestMessageId parameter controls pagination boundaries. Each call to getHistoryMessages uses the message pointed to by oldestMessageId as a boundary to return the specified number of messages on the next page. To retrieve the latest count messages in the conversation, set oldestMessageId to -1.
We recommend using the messageId of the earliest message in the returned results as the oldestMessageId for subsequent calls to traverse the entire conversation history.
| Parameter | Type | Description |
|---|---|---|
| conversationType | [RCConversationType] | Conversation type |
| targetId | NSString | Conversation targetId |
| channelId | NSString | Ultra group channel ID |
| oldestMessageId | long | Uses this messageId as boundary to retrieve count messages with smaller timestamps. Set to -1 when ID doesn't exist to retrieve the latest count messages. |
| count | int | Number of messages to retrieve. |
| completion | Block | Message retrieval callback. |
Sample Code
[[RCChannelClient sharedChannelManager] getHistoryMessages:ConversationType_ULTRAGROUP
targetId:@"targetId"
channelId:@"channelId"
oldestMessageId:-1
count:10
completion:^(NSArray<RCMessage *> * _Nullable messages) {
}];
### Retrieve Messages Around a Specified Timestamp
:::tip
This feature is supported for Ultra Groups starting from version 5.3.0.
:::
Asynchronously retrieves the latest message entities before and after a specified timestamp in the conversation, returning a list of `RCMessage` objects.
#### Method Signature
```objectivec
- (void)getHistoryMessages:(RCConversationType)conversationType
targetId:(NSString *)targetId
channelId:(nullable NSString *)channelId
sentTime:(long long)sentTime
beforeCount:(int)beforeCount
afterCount:(int)afterCount
completion:(nullable void(^)(NSArray<RCMessage *> * _Nullable messages))completion;
#### Parameter Description
| Parameter | Type | Description |
|:-----------------|:---------------------|:------------------------------------------|
| conversationType | [RCConversationType] | Conversation type |
| targetId | NSString | Target ID of the conversation |
| channelId | NSString | Ultra Group channel ID |
| sentTime | long long | Timestamp used as the boundary to retrieve messages before or after this time. |
| beforeCount | int | Number of messages to retrieve that were sent before the specified timestamp. |
| afterCount | int | Number of messages to retrieve that were sent after the specified timestamp. |
| completion | Block | Callback for retrieved messages. |
#### Sample Code
```objectivec
[[RCChannelClient sharedChannelManager] getHistoryMessages:ConversationType_ULTRAGROUP
targetId:@"targetId"
channelId:@"channelId"
sentTime:0
beforeCount:10
afterCount:10 completion:^(NSArray<RCMessage *> * _Nullable messages) {
}];
### Retrieve Messages of a Specified Type in a Conversation
#### Method Signature
```objectivec
- (void)getHistoryMessages:(RCConversationType)conversationType
targetId:(NSString *)targetId
channelId:(nullable NSString *)channelId
objectName:(nullable NSString *)objectName
oldestMessageId:(long)oldestMessageId
count:(int)count
completion:(nullable void(^)(NSArray<RCMessage *> * _Nullable messages))completion;
#### Parameter Description
| Parameter | Type | Description |
|:-----------------|:---------------------|:-----------------------------------------------------------------------------------------------------|
| conversationType | [RCConversationType] | Conversation type |
| targetId | NSString | Target ID of the conversation |
| channelId | NSString | Ultra Group channel ID |
| objectName | NSString | Message type identifier. For built-in message type identifiers, refer to [Message Type Overview]. |
| oldestMessageId | long | Uses this message ID as the boundary to retrieve `count` messages with earlier send times. Set to -1 to retrieve the latest `count` messages when the ID doesn't exist. |
| count | int | Number of messages to retrieve. |
| completion | Block | Callback for retrieved messages. |
#### Sample Code
```objectivec
[[RCChannelClient sharedChannelManager] getHistoryMessages:ConversationType_ULTRAGROUP
targetId:@"targetId"
channelId:@"channelId"
objectName:@"RC:TxtMsg"
oldestMessageId:-1
count:10
completion:^(NSArray<RCMessage *> * _Nullable messages) {
}];
To retrieve historical messages before or after a specified message, use the following method with the `isForward` parameter:
#### Method Signature
```objectivec
- (void)getHistoryMessages:(RCConversationType)conversationType
targetId:(NSString *)targetId
channelId:(nullable NSString *)channelId
objectName:(nullable NSString *)objectName
baseMessageId:(long)baseMessageId
isForward:(BOOL)isForward
count:(int)count
completion:(nullable void(^)(NSArray<RCMessage *> * _Nullable messages))completion;
#### Parameter Description
| Parameter | Type | Description |
|:-----------------|:---------------------|:--------------------------------------------------------------------|
| conversationType | [RCConversationType] | Conversation type. |
| targetId | NSString | Target ID of the conversation. |
| channelId | NSString | Ultra Group channel ID. |
| objectName | NSString | List of message type identifiers. For built-in message type identifiers, refer to [Message Type Overview]. |
| baseMessageId | long | Uses this message ID as the boundary to retrieve historical messages before or after it. |
| isForward | BOOL | `YES` retrieves messages before the specified timestamp. `NO` retrieves messages after the specified timestamp. |
| count | int | Number of messages to retrieve. |
| completion | Block | Callback for retrieved messages. |
#### Sample Code
```objectivec
[[RCChannelClient sharedChannelManager] getHistoryMessages:ConversationType_ULTRAGROUP
targetId:@"targetId"
channelId:@"channelId"
objectName:@"RC:TxtMsg"
baseMessageId:-1
isForward:true
count:10
completion:^(NSArray<RCMessage *> * _Nullable messages) {
}];
### Retrieve Historical Messages of Multiple Specified Types
You can retrieve the latest message entities of multiple specified types from a conversation, either before or after a designated message, with a specified quantity, asynchronously returning a list of `RCMessage` objects.
#### Interface Prototype
```objectivec
- (void)getHistoryMessages:(RCConversationType)conversationType
targetId:(NSString *)targetId
channelId:(nullable NSString *)channelId
objectNames:(NSArray<NSString *> *)objectNames
sentTime:(long long)sentTime
isForward:(BOOL)isForward
count:(int)count
completion:(nullable void(^)(NSArray<RCMessage *> * _Nullable messages))completion;
#### Parameter Description
| Parameter | Type | Description |
|:-----------------|:---------------------|:---------------------------------------------------------------------------|
| conversationType | [RCConversationType] | Conversation type. |
| targetId | NSString | Conversation targetId. |
| channelId | NSString | Ultra group channel channelId. |
| objectNames | NSArray | List of message type identifiers. Built-in message type identifiers can be found in [Message Type Overview]. |
| sentTime | long long | Timestamp used as a boundary to retrieve messages before or after this time. |
| isForward | BOOL | `YES` retrieves messages before the specified timestamp. `NO` retrieves messages after the specified timestamp. |
| count | int | Number of messages to retrieve. |
| completion | Block | Callback for retrieved messages. |
#### Example Code
```objectivec
[[RCChannelClient sharedChannelManager] getHistoryMessages:ConversationType_ULTRAGROUP
targetId:@"targetId"
channelId:@"channelId"
objectNames:@[@"RC:TxtMsg"]
sendtTime:0
isForward:true
count:10
completion:^(NSArray<RCMessage *> * _Nullable messages) {
}];
Ultra groups also support extracting messages from the local database using messageUId. For details, see **Retrieve Messages by messageUId** in [Retrieve Historical Messages](../message/get-history.md).
## Retrieve Remote Historical Messages \{#getmsgremote}
Starting from version 5.6.4, the IMLib SDK supports using the `getRemoteHistoryMessages` method of `RCChannelClient` to directly query historical messages stored in **Cloud Storage for Ultra Group Messages** for specified ultra group conversations.
:::tip
Whether users can retrieve historical messages from before they joined the ultra group depends on the settings of the corresponding App Key in the RC Console. By default, new group members can only see group messages sent after they joined. For configuration methods, see [Enable Ultra Group Service](https://help.rongcloud.cn/t/topic/1057).
:::
### Custom Retrieval of Remote Historical Messages for Conversations
You can customize the behavior of the `getRemoteHistoryMessages` method using `RCRemoteHistoryMsgOption` to retrieve remote historical messages that meet the specified conditions. The IMLib SDK will directly query **Cloud Storage for One-to-One and Group Messages** for historical messages that match the query criteria.
:::tip
- By default, the `getRemoteHistoryMessages` method returns messages after deduplication with local messages. It is recommended to first use `getHistoryMessages` to retrieve all messages from the local database, then use the `sentTime` of the last local message as `recordTime` to fetch remote historical messages. This method cannot retrieve missing messages. To retrieve missing messages, use the `getMessages` interface to fetch both local and remote historical messages.
:::
#### Interface Prototype
```objectivec
- (void)getRemoteHistoryMessages:(RCConversationType)conversationType
targetId:(NSString *)targetId
channelId:(nullable NSString *)channelId
option:(RCRemoteHistoryMsgOption *)option
success:(nullable void (^)(NSArray<RCMessage *> *messages, BOOL isRemaining))successBlock
error:(nullable void (^)(RCErrorCode status))errorBlock;
#### Parameter Description
`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 fetch messages either before or after the given `recordTime`. The `includeLocalExistMessage` parameter determines whether the returned message list should include messages already present in the local database.
By default, `RCRemoteHistoryMsgOption` queries messages in descending order of their sent time and compares the results with the local database to exclude duplicate messages before returning the message object list. When `includeLocalExistMessage` is set to `NO`, it is recommended that the app layer first uses `getHistoryMessages` to retrieve all messages from the local database before fetching remote historical messages; otherwise, locally existing messages might not be retrieved.
To query messages in ascending order of their sent time, it is recommended to use the `sentTime` of the latest message in the returned results as the `recordTime` value for the next call, enabling traversal of the entire conversation's message history. Ascending order queries are typically useful for scenarios where you need to fetch newer historical messages after jumping to a specific message position in the conversation UI.
| Parameter | Type | Description |
|:-----------------|:-------------------------|:-------------------------------------------|
| conversationType | [RCConversationType] | Conversation type. |
| targetId | NSString | Ultra group conversation targetId. |
| channelId | NSString | Ultra group channel channelId. |
| option | RCRemoteHistoryMsgOption | Configurable parameters, including fetch count and order. |
| successBlock | Block | Callback for successful retrieval. |
| errorBlock | Block | Callback for failed retrieval. |
- **`RCRemoteHistoryMsgOption` Description**:
| Parameter | Description |
|:-------------------------|:--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| recordTime | Timestamp for controlling the boundary of paginated message queries. Default value is `0`. |
| count | Number of messages to fetch. For SDK versions < 5.4.1, range is [2-20]; for SDK versions ≥ 5.4.1, range is [2-100]; default value is `0`, indicating no fetch. |
| order | Fetch order. `RCRemoteHistoryOrderDesc`: Descending order, retrieves messages with send time earlier than `recordTime` in chronological descending order, returning messages from newest to oldest. `RCRemoteHistoryOrderAsc`: Ascending order, retrieves messages with send time later than `recordTime` in chronological ascending order, returning messages from oldest to newest. Default is `RCRemoteHistoryOrderDesc`. |
| includeLocalExistMessage | Whether to include existing messages from local database. `YES`: Includes, query results are not deduplicated against local database, directly returning historical messages fetched from server. `NO`: Excludes, query results are first deduplicated against local database, only returning messages not existing locally. Default is `NO`. |
- `success` Description:
| Callback Parameter | Callback Type | Description |
|:------------|:---------|:-------------------|
| messages | NSArray | Retrieved historical message array |
| isRemaining | BOOL | Whether more messages remain |
- `error` Description:
| Callback Parameter | Callback Type | Description |
|:---------|:--------------------------------------------------------------------------------------------------------------------------------|:---------------|
| status | [RCErrorCode](https://doc.rongcloud.cn/apidoc/imlibcore-ios/latest/zh_CN/documentation/rongimlibcore/rcerrorcode?language=objc) | Error code for failed fetch |
#### Sample Code
```objectivec
RCRemoteHistoryMsgOption *option = [RCRemoteHistoryMsgOption new];
option.recordTime = recordTime;
option.count = 10;
option.order = RCRemoteHistoryOrderDesc;
option.includeLocalExistMessage = NO;
[[RCChannelClient sharedChannelManager] getRemoteHistoryMessages:ConversationType_ULTRAGROUP targetId:@"targetId" channelId:@"channelId" option:option success:^(NSArray<RCMessage *> * _Nonnull messages, BOOL isRemaining) {
} error:^(RCErrorCode status) {
///
}];
|
### Force Fetch Specific Batch Messages from Server
You can use the `getBatchRemoteUltraGroupMessages:` interface to forcibly fetch corresponding messages from the server. Upon successful retrieval, local messages will be forcibly updated.
#### Interface Prototype
```objectivec
- (void)getBatchRemoteUltraGroupMessages:(NSArray <RCMessage*>*)messages
success:(void (^)(NSArray *matchedMsgList, NSArray *notMatchMsgList))successBlock
error:(void (^)(RCErrorCode status))errorBlock
#### Parameter Description
| Parameter | Type | Description |
|:-----------------|:---------------------|:--------------------------------------------------------------------|
| messages | NSArray | Message list. Maximum 20 messages. All messages must be of ultra group type and belong to the same conversation. Each message object must contain valid values for ConversationType, targetId, channelId, messageUid, and sentTime. |
| successBlock | Block | Callback for successful message count query. matchedMsgList contains messages successfully fetched from server; notMatchMsgList contains messages with invalid parameters (if any), or indicates no matching messages were found. |
| errorBlock | Block | Callback for failed message count query. |
#### Sample Code
## Count Local Historical Messages
:::tip
`RCChannelClient` supports this capability starting from version 5.6.4.
:::
You can retrieve the message count for a specified ultra group within a given time range. This method supports passing a channel list. If no channels are specified, it returns the count of all local historical messages across all channels.
#### Interface Prototype
```objectivec
- (void)getUltraGroupMessageCountByTimeRange:(NSString *)targetId
channelIds:(NSArray<NSString *> *)channelIds
startTime:(long long)startTime
endTime:(long long)endTime
success:(nullable void (^)(NSInteger count))successBlock
error:(nullable void (^)(RCErrorCode status))errorBlock;
#### Parameter Description
| Parameter | Type | Description |
|:-----------------|:---------------------|:--------------------------------------------------------------------|
| targetId | NSString | Ultra group conversation targetId |
| channelIds | NSArray | Ultra group channelId list |
| sentTime | long long | Query messages after startTime, where startTime >= 0. |
| endTime | long long | Query messages before endTime, where endTime > startTime. |
| successBlock | Block | Callback for successful message count query, returning the corresponding message count. |
| errorBlock | Block | Callback for failed message count query. |
#### Sample Code
```objectivec
[[RCChannelClient sharedChannelManager] getUltraGroupMessageCountByTimeRange:@"targetId" channelIds:@[@"channelId"] startTime:0 endTime:endTime success:^(NSInteger count) {
} error:^(RCErrorCode status) {
}];
<!--links-->
[Message Type Overview]: /platform-chat-api/message-about/about-message-types
<!-- api links -->
[RCConversationType]: https://doc.rongcloud.cn/apidoc/imlibcore-ios/latest/zh_CN/documentation/rongimlibcore/rcconversationtype?language=objc
[getMessages]: https://doc.rongcloud.cn/apidoc/imlibcore-ios/latest/zh_CN/documentation/rongimlibcore/rcchannelclient/getmessages(_:targetid:channelid:option:complete:)?language=objc
[RCErrorCode]: https://doc.rongcloud.cn/apidoc/imlibcore-ios/latest/zh_CN/documentation/rongimlibcore/rcerrorcode?language=objc