Message History

Update time: 2021/12/06 06:49:18

CommsEase supports storing historical messages locally and on the cloud.

Local historical messages

Query local historical messages

Prototype

objc@protocol NIMConversationManager <NSObject>
/**
 * Read several messages sent before a certain message in a session from local db
 *
 * @param session - A message in a certain session
 * @param message - The current earliest message. If there is no such message, import nil.
 * @param limit - The maximum number of messages
 *
 * @return - List of messages. The messages are sorted in ascending order by time.
 */
- (nullable NSArray<NIMMessage *> *)messagesInSession:(NIMSession *)session
                                              message:(nullable NIMMessage *)message
                                                limit:(NSInteger)limit;
@end

Property List

Parameter Type Description
session NIMSession A message in a session
message NIMMessage Anchor messages
limit NSInteger The maximum number of read count.

Input a known message (anchor message), and return an earlier message set. Input nil, if no known message exists, and return the latest message set. The search results are ranked from old to new ones.

Example

objc// NIMSessionMsgDatasource.m

- (void)resetMessages:(void(^)(NSError *error)) handler
{    
    ...
    //Get final limit messages from local session and add them to the end of data
    NSArray<NIMMessage *> *messages = [[[NIMSDK sharedSDK] conversationManager] messagesInSession:_currentSession
                                                                                message:nil
                                                                                    limit:_messageLimit];
    [self appendMessageModels:[self modelsWithMessages:messages]];
    ...
}

Query by message IDs

objc@protocol NIMConversationManager <NSObject>
/**
 * Get messages by message ID
 *
 * @param session - A combination of a message session
 * @param messageIds - A set of message IDs
 * @return - A list of messages. The messages are sorted in ascending order by time.
 */
- (nullable NSArray<NIMMessage *> *)messagesInSession:(NIMSession *)session
                                           messageIds:(NSArray<NSString *> *)messageIds;
@end

Property List

Parameter Type Description
session NIMSession A message in a session
messageIds NSArray<NSString *> A set of message IDs.

Delete local messages

Delete a message

objc
@protocol NIMConversationManager <NSObject>

/**
 * Delete a certain message
 *
 * @param message - Sessions to be deleted
 * @param option - Delete options
 */
- (void)deleteMessage:(NIMMessage *)message 
               option:(nullable NIMDeleteMessageOption *)option;

@end

With the method, if the last message is deleted, the last message of the recent session will be automatically changed to the previous message (null if none), which will also trigger the callback of modification to the recent messages.

removeFromDB can be configured in NIMDeleteMessageOption. By default, the value is "NO". If set as "YES", the SDK records the deletion of the message. You can not query the deleted message from the database even though the message is synced on the cloud.

Delete the message in a specified session

objc@protocol NIMConversationManager <NSObject>
/**
 * Delete all messages in a certain session
 *
 * @param session - A session to be deleted
 * @param option - Options for deleting messages
 */
- (void)deleteAllmessagesInSession:(NIMSession *)session
                            option:(nullable NIMDeleteMessagesOption *)option;
@end

NIMDeleteMessagesOption Parameter List

Parameter Type Description
removeSession BOOL In relation to the options "whether to remove related recent sessions" and "whether to remove recent sessions when messages are deleted in batches", "NO" is in default. If the options are set to YES, recent session messages will be deleted meanwhile.
removeTable BOOL In relation to the option "whether to delete the message table", CommsEase deletes messages by tag in default. If the option is set to YES, the related message table will be removed together, thus reducing the number of message tables and accelerating I/O. NO is in default, representing tag deletion. After a message deleted is pulled from the cloud and set to be synchronized to the database, the message still cannot be searched.

To delete the messages within a period, use the following APIs:

objc@protocol NIMConversationManager <NSObject>
/**
 * Delete messages of a designated scope, such as a designated time range
 *
 * @param session - A target session
 * @param option - Options for deleting messages
 */
- (void)deleteMessagesInSession:(NIMSession *)session 
                         option:(nullable NIMBatchDeleteMessagesOption *)option 
                     completion:(nullable NIMBatchDeleteMessagesBlock)block;
@end

NIMBatchDeleteMessagesOption Parameter List

Parameter Type Description
start NSTimeInterval The start time. By default, the parameter value is set as 0 (unit: s). The value no greater than 0 represents all the previous messages.
end NSTimeInterval The end time. By default, the parameter value is set as 0 (unit: s). The value no greater than 0 represents the current time.

Delete all messages

objc@protocol NIMConversationManager <NSObject>
/**
 * Delete all session messages.
 *
 * @param option - Options for deleting messages
 * @discussion - Invoking The API will trigger the callback of allMessagesDeleted only. Other callbacks for a single recentSession will not be invoked.
 */
- (void)deleteAllMessages:(NIMDeleteMessagesOption *)option
@end

Historical messages on the cloud

Query historical messages on the cloud

objc@protocol NIMConversationManager <NSObject>
/**
 * Get several messages before a certain message in a session from server
 *
 * @param session - A message in a session
 * @param result - The result of a list of read messages
 * @discussion - You can not query messages in a chat room. For information on the chat room, see the "Query messages" API in NIMChat roomManagerProtocol.
 *
 */
- (void)fetchMessageHistory:(NIMSession *)session
                     option:(NIMHistoryMessageSearchOption *)option
                     result:(nullable NIMGetMessageHistoryBlock)result;
@end

The parameter option is used to search. Specific options are as follows:

Parameter Type Description
startTime NSTimeInterval The start time to search; Import 0 if no start time.
endTime NSTimeInterval The end time. By default, the parameter value is 0, representing the current time. The end time should be greater than the start time. The parameter is invalid for the room chat sessions.
limit NSUInteger The maximum queries is up to 100
order NIMMessageSearchOrder The search order. NIMMessageSearchOrderDesc means searching messages from the latest to previous messages. The results are ranked from new to old ones); NIMMessageSearchOrderAsc means the search from old to new messages (and the results are ranked from old to new ones). The parameter is invalid for the room chat sessions
currentMessage NIMMessage Message as a start for search (the search result will not cover the message).

In the event of NIMMessageSearchOrderDesc, when the currentMessage is set, the endTime must be set as the timestamp of the message. In the event of NIMMessageSearchOrderAsc, when the currentMessage is set, the startTime must be set as the timestamp of the message. The parameter is invalid for the room chat sessions. | sync| BOOL| Whether to sync to the local database after the remote access to messages, (the sync will only ensure that the message data will be written in locally, without triggering callback). NO is in default. The parameter is invalid for the room chat sessions | messageTypes| NSArray <NSNumber *>*| The combination of message types is nil in default for all-type search. Once the field is set, the field sync will become invalid, and the search result will not be written in db. | customFilter| NIMHistoryMessageFilterBlock| Custom message filter. Return YES means the message is filtered without being written in database or called back; return NO means that the message is written in database and called back

Delete historical messages on the cloud

Delete cloud historical messages of a single session

objc@protocol NIMConversationManager <NSObject>

/**
 * Clear server messages in peer-to-peer sessions. Local historical messages will not be deleted.
 *
 * @param session - Target sessions
 * @param option - Options for clearing messages
 * @param completion  The callback is completed.
 * @discussion - It is available to peer-to-peer session. Clearing server messages of one user will not influence the other user. If the clear option is not configured, the server will also clear roaming messages by default.
 */
- (void)deleteSelfRemoteSession:(NIMSession *)session
                         option:(nullable NIMClearMessagesOption *)option
                     completion:(nullable NIMRemoveRemoteSessionBlock)completion;              
@end

Property List

Parameter Type Description
sessions NIMSession Sessions
option NIMClearMessagesOption With regard to the option "whether to clear server roaming messages meanwhile", the messages will be deleted by default if nil.
completion NIMRemoveRemoteSessionBlock Delete remote session error callback

Delete a historical message on the cloud

objc@protocol NIMConversationManager <NSObject>

/**
 * Delete a certain local message, and delete historical and roaming messages.
 *
 * @param message - Chat messages to be deleted
 * @param ext - Extension field
 * @param completion  The callback is completed
 */
- (void)deleteMessageFromServer:(NIMMessage *)message 
                            ext:(nullable NSString *)ext 
                     completion:(nullable NIMRemoveRemoteMessageBlock)block         
@end

Delete cloud historical messages in batch

objective-c@protocal NIMConversationManager <NSObject>

/**
 * Delete messages in batch, and delete messages of the server and local messages. All input messages must be taken from the same session.
 *
 * @param messages - The array of messages
 * @param exts key is the Message ID. The value is the extension information corresponding to the deleted message.
 * @param completion - The callback that messages in batches are deleted.
 */
- (void)deleteRemoteMessages:(NSArray<NIMMessage *> *)messages
                        exts:(nullable NSDictionary<NSString *,NSString *> *)exts
                  completion:(nullable NIMDeleteRemoteMessagesCompletionBlock)completion;

@end

Clear cloud historical messages from a session

objective-c@protocol NIMConversationManager <NSObject>
  
 /**
 * Delete all local and cloud message history in a certain session. After deletion, The API for querying cloud historical messages can not return these deleted messages.
 *
 * @param session - Target sessions
 * @param options - Options for clearing historical messages
 * @param block - The callback that historical messages are deleted
 */
- (void)deleteAllRemoteMessagesInSession:(NIMSession *)session
                                 options:(NIMSessionDeleteAllRemoteMessagesOptions *)options
                              completion:(NIMSessionDeleteAllRemoteMessagesCompletionBlock)completion;
@end

Property List

Parameter Type Description
session NIMSession Sessions to be cleared
options NIMSessionDeleteAllRemoteMessagesOptions Options for clearing historical messages
completion NIMSessionDeleteAllRemoteMessagesCompletionBlock The callback that historical messages are deleted

Messages retrieval

SDK currently supports message retrieval.

Local messages retrieval

Retrieval by sessions

objc@protocol NIMConversationManager <NSObject>
/**
 * Search messages in a local session
 *
 * @param session - A message in a session
 * @param option - Search options
 * @param result - Result of the list of read messages
 *
 */
- (void)searchMessages:(NIMSession *)session
                option:(NIMMessageSearchOption *)option
                result:(nullable NIMSearchMessageBlock)result;
@end

The parameter option is used to search. Specific options are as follows:

Parameter Type Description
startTime NSTimeInterval The start time. By default, the parameter value is 0.
endTime NSTimeInterval The end time. By default, the parameter value is 0, which indicates the maximum timestamp. Ensure the endTime must be later than the startTime.
limit NSUInteger The number of retrievals. By default, the number is set as 0, which indicates unlimited retrievals.
order NIMMessageSearchOrder In relation to search order, NIMMessageSearchOrderDesc is in default, which means the search from new to old messages; NIMMessageSearchOrderAsc means the search from old to new messages. Regardless of the search order, the search results are ranked from old to new ones.
messageTypes NSArray<NSNumber *> The combination of message types. By default, only text types are searched. The parameter is valid when allMessageTypes is set as NO.
messageSubTypes NSArray<NSNumber*> * The combination of message subtypes searched
allMessageTypes BOOL Search all message types. By default, the parameter value is set as 0. If set as YES, ignore the messageType and return all message types.
searchContent NSString Search text. If the message type to be searched is text, content matching will be conducted.
fromIds NSArray<NSString *> The list of message initiators
enableContentTransfer BOOL Escape regular special characters in the searched text. By default, the parameter value is set as YES.

Search will return: the time between startTime and endTime, specified message type; match with the searched contents or a certain number of messages in the message initiator list.

Examples for the latest 100 messages searched by key words:

objcNIMMessageSearchOption *option = [[NIMMessageSearchOption alloc] init];
option.searchContent = @"keyWord";
option.fromIds    = uids;
option.limit     = 100;
option.allMessageTypes = YES;

[[NIMSDK sharedSDK].conversationManager searchMessages:session option:option result:^(NSError * _Nullable error, NSArray<NIMMessage *> * _Nullable messages) {
    // do something with messages
}];

Global local retrieval

objc@protocol NIMConversationManager <NSObject>
/**
 * Global search for local messages
 *
 * @param option - Search options
 * @param result - Content of read messages
 */
- (void)searchAllMessages:(NIMMessageSearchOption *)option
                result:(NIMGlobalSearchMessageBlock)result
@end

The parameter option is used to search. Specific options are as follows:

Parameter Type Description
startTime NSTimeInterval The start time. By default, the parameter value is 0.
endTime NSTimeInterval The end time. By default, the parameter value is 0, which indicates the maximum timestamp. Ensure the endTime must be later than the startTime.
limit NSUInteger The number of retrievals. By default, the number is set as 0, which indicates unlimited retrievals.
order NIMMessageSearchOrder In relation to search order, NIMMessageSearchOrderDesc is in default, which means the search from new to old messages; NIMMessageSearchOrderAsc means the search from old to new messages. Regardless of the search order, the search results are ranked from old to new ones.
messageTypes NSArray<NSNumber *> The combination of message types. By default, only text types are searched. The parameter is valid when allMessageTypes is set as NO.
messageSubTypes NSArray<NSNumber*> * The combination of message subtypes searched
allMessageTypes BOOL Search all message types. By default, the parameter value is set as 0. If set as YES, ignore the messageType and return all message types.
searchContent NSString Search text. If the message type to be searched is text, content matching will be conducted.
fromIds NSArray<NSString *> Message initiator list
enableContentTransfer BOOL Escape regular special characters in the searched text; YES in default

Search will return: the time between startTime and endTime, specified message type; match with the searched contents or a certain number of messages in the message initiator list.

Example for the latest 100 messages of pictures and videos searched globally:

objcNIMMessageSearchOption *option = [[NIMMessageSearchOption alloc] init];
option.limit = 100;

[[NIMSDK sharedSDK].conversationManager searchAllMessages:option result:^(NSError * _Nullable error, NSDictionary<NIMSession *,NSArray<NIMMessage *> *> * _Nullable messages) { }];

Retrieve cloud messages by key words

Retrieve the text contents of server historical messages by keywords, and complete paging and other features by setting the start time and the end time; The feature is supported for peer-to-peer and team messages. Supergroup is not supported now.

objc/**
 * Session manager
 */
@protocol NIMConversationManager <NSObject>
    /**
     * Retrieve messages from the server by keywords
     *
     * @param session - A message in a session
     * @param option - Retrieval options
     * @param result - Result of the list of read messages
     * @discussion - Retrieve message content, without limit in capital and small letter. This API is not available to query chat room messages. For the chat room, see the message API in NIMChat roomManagerProtocol.
     *
     */
    - (void)retrieveServerMessages:(NIMSession *)session
                            option:(NIMMessageServerRetrieveOption *)option
                            result:(nullable NIMRetrieveServerMessagesBlock)result;
@end

Property List

Parameter Type Description
session NIMSession The current session
option NIMMessageServerRetrieveOption Retrieval options
result NIMRetrieveServerMessagesBlock The callback of a result.

Example

objc    NSString * keyword = searchBar.text;
    NIMMessageServerRetrieveOption * option = [[NIMMessageServerRetrieveOption alloc] init];
    option.keyword = keyword;
    [[NIMSDK sharedSDK].conversationManager retrieveServerMessages:self.session
                                                            option:option
                                                            result:^(NSError * _Nullable error,
                                                                     NSArray<NIMMessage *> * _Nullable messages)
    {
     ...
    }];
Was this page helpful?
Yes
No
  • Local historical messages
  • Query local historical messages
  • Query by message IDs
  • Delete local messages
  • Delete a message
  • Delete the message in a specified session
  • Delete all messages
  • Historical messages on the cloud
  • Query historical messages on the cloud
  • Delete historical messages on the cloud
  • Delete cloud historical messages of a single session
  • Delete a historical message on the cloud
  • Delete cloud historical messages in batch
  • Clear cloud historical messages from a session
  • Messages retrieval
  • Local messages retrieval
  • Retrieval by sessions
  • Global local retrieval
  • Retrieve cloud messages by key words