Recent session

Update time: 2023/02/09 08:29:38

Overview

Session

The session in the SDK is represented by NIMSession. The SDK supports p2p sessions, group sessions, chat room sessions.

Prototype

objc@interface NIMSession : NSObject<NSCopying>

/**
 *  Session ID. If the current session type is team, use teamId as sessionId, and peer account for P2P type
 */
@property (nonatomic,copy,readonly)         NSString *sessionId;

/**
 *  Session type. P2P, team, and chat room are supported
 */
@property (nonatomic,assign,readonly)       NIMSessionType sessionType;

/**
 *  Construct a session object using id and type
 *
 *  @param sessionId   session ID
 *  @param sessionType session type
 *
 *  @return an instance of the session object
 */
 + (instancetype)session:(NSString *)sessionId
                   type:(NIMSessionType)sessionType;

@end

When using NIMSession, you don't need to get the session object. Construct it according to the existing session Id and type. Example:

objc//p2p
NIMSession *myFriendSession = [NIMSession session:@"friend user id" type:NIMSessionTypeP2P];

//team
NIMSession *teamSession = [NIMSession session:@"team id" type:NIMSessionTypeTeam];

//do something with session

Local recent sessions

The local recents session is used to represent the data model of recent contacts. When the user sends or receives messages., the recent session will be updated at the same time.

When a message is received from a new contact, the SDK will automatically generate the local recent session for this message. local recent sessions and sessions are not in a one-to-one correspondence. Deleting recent sessions will not affect sessions.

The local recent session is represented by NIMSession

objc/**
 *  Recent session
 */
@interface NIMRecentSession : NSObject

/**
 *  Current session
 */
@property (nullable,nonatomic,readonly,copy)   NIMSession  *session;

/**
 *  Last message
 */
@property (nullable,nonatomic,readonly,strong)   NIMMessage  *lastMessage;

/**
 * The number of unread messages. To ensure thread security, get the data in the main thread
 */
@property (nonatomic,readonly,assign)   NSInteger   unreadCount;

/**
 * Local extension field
 */
@property (nullable,nonatomic,readonly,copy) NSDictionary *localExt;

@end

Properties

Parameter Type Description
session NIMSession Current session
lastMessage NIMMessage The last message in the current session.
unreadCount NSInteger The number of unread messages. To ensure thread security, get the data in the main thread
localExt NSDictionary The local extension of the recent session. After modification, you must call the updateRecentLocalExt:recentSession: method in NIMConversationManagerProtocol to store it locally

Get recent sessions

Get recent sessions

Get recent sessions displayed in the homepage.

Prototype

objc@protocol NIMConversationManager <NSObject>
/**
 *  Get all recent sessions
 *  @discussion Call the method in the main thread.
 * @return list of all recent sessions
 */
- (nullable NSArray<NIMRecentSession *> *)allRecentSessions;
@end

Example

objc//  NIMSessionListViewController.m
- (void)viewDidLoad {
    ...
    NSArray *recentSessions = [NIMSDK sharedSDK].conversationManager.allRecentSessions;
    ...
}

To ensure thread safety, call this method on the main thread. Since the recent session is stored in a dictionary, the data will be sorted in use. The operation takes a certain amount of time when the amount of data points exceeds 10,000.

To handle too many recent sessions, starting from version v7.0.0, the SDK provides an asynchronous loading completion callback;

objc@protocol NIMConversationManagerDelegate <NSObject>
/**
*  Callback when all recent sessions are fetched from the database
*
* @discussion All recent sessions are read. This callback will be invoked when the asyncLoadRecentSessionEnabled propertty in NIMSDKConfig is set to YES.
* The execution of this callback indicates that all recent sessions have been loaded, and all recent sessions can be retrieved using allRecentSessions.
*/
- (void)didLoadAllRecentSessionCompletion;
@end

Note:

  • Set the asyncLoadRecentSessionEnabled property of NIMSDKConfig to YES at the same time.
  • When there are many local sessions and the processing takes a long time: the SDK is querying sessions > the user calls allRecentSessions > the SDK has not returned all sessions at this time > the SDK queries all the sessions > SDK trigger the callback -didLoadAllRecentSessionCompletion > the user calls allRecentSessions again to obtain complete sessions and update the UI.
  • In the case of fewer local sessions, when the user calls allRecentSessions, the callback will not be triggered if the SDK has returned all sessions.

Get custom recent sessions

You can call the allRecentSessionsWithOption method and set the filterLastMessageTypes parameter of the NIMRecentSessionOption class to filter the type of the last message of the recent session and return the list of recent sessions whose last message is not filtered.

  • The recent sessions returned by this method are all new objects. All callbacks for recent sessions will not return the session returned by calling this method.
  • This method is only suitable for the case where the last message type in the session list needs to be filtered, and when the amount of data is large (tens of thousands messages), it will take time to return the sessions. In most cases, use [allRecentSessions](https://doc.commsease.com/docs/interface/instant messaging iOS terminal/NIMSDK-iOS/Protocols/NIMConversationManager.html#//api/name/allRecentSessions) method to get a list of recent sessions.

API prototype

objc@protocol NIMConversationManager <NSObject>
/**
 *  Get all recent sessions
 * @return list of all recent sessions
 * @discussion The SDK saves recent sessions in NSArray. When calling this method, sessions will be sorted. It will be time-consuming when the amount of data is large.
 *  Different from the result returned by allRecentSessions, the recent sessions returned by this interface are new object created based on  allRecentSessions.
 * You must manage on your own, and all callbacks do not return any session queried by this interface.
 */
- (nullable NSArray<NIMRecentSession *> *)allRecentSessionsWithOption:(NIMRecentSessionOption *)option;

Sample code

objc// Query all recent sessions, and return the last non-notification message of the recent session
- (void)getAllRecentSessionTests {
 NIMRecentSessionOption *option = [[NIMRecentSessionOption alloc] init];
 option.filterLastMessageTypes = @[@(NIMMessageTypeNotification)];
 NSArray *sessions = [[NIMKit shareKit].conversationManager allRecentSessionsWithOption:option];
}

Get the specified recent sessions

Starting from v5.9.0, you can obtain the corresponding session using the session ID.

objc@protocol NIMConversationManager <NSObject>
/**
 * Return the corresponding recent session information based on the current session
 */
- (nullable NIMRecentSession *)recentSessionBySession:(NIMSession *)session
@end

Create a recent sessions list

The SDK supports creating recent sessions:

  • Prototype

Without configuration

objc@protocol NIMConversationManager <NSObject>
/**
 *  Add a recent session
 *
 *@param session session to be added
 *  @discussion asynchronous method call
 */
- (void)addEmptyRecentSessionBySession:(NIMSession *)session;
@end

With configuration

objc@protocol NIMConversationManager <NSObject>
/**
 *  Add a recent session
 *
 *@param session session to be added
 *  @param option option
 *  @discussion asynchronous method call
 */
- (void)addEmptyRecentSessionBySession:(NIMSession *)session option:(NIMAddEmptyRecentSessionBySessionOption *) option;
@end

NIMAddEmptyRecentSessionBySessionOption

objc@interface NIMAddEmptyRecentSessionBySessionOption : NSObject
/**
 * Specify whether to add the last message
 *  @discussion. Default value is NO. Only empty session is created. If the default value is set to Yes, the last message is added.
 */
@property   (nonatomic,assign)  BOOL    withLastMsg;

/**
 *  If the last message is not added, specify whether to add an empty message as placeholder
 *  @discussion The default value is YES. An empty message is created as placeholder. If the default value is set to NO, no placeholder message is added.
 */
@property   (nonatomic,assign)  BOOL    addEmptyMsgIfNoLastMsgExist;
@end

Update the recent session list

Recent sessions provide local extension capabilities, which can be used to develop functions such as @mension and pinned.

Prototype

objc@protocol NIMConversationManager <NSObject>
/**
 * Update local extension for recent sessions
 *
 *  @param ext        extension
 *  @param recentSession    Recent session to be updated
 * @discussion This extension will not be synced with other clients. tThe upper layer must ensure that NSDictionary can be converted to JSON.
 */
- (void)updateRecentLocalExt:(nullable NSDictionary *)ext
               recentSession:(NIMRecentSession *)recentSession;

@end

Properties

Parameter Type Description
ext NSDictionary Extension, The upper layer must ensure that NSDictionary can be converted to JSON
recentSession NIMRecentSession Recent session to be updated

Example

objc// NTESSessionUtil.m
+ (void)addRecentSessionAtMark:(NIMSession *)session
{
    //Add someone @your mark to the session
    NIMRecentSession *recent = [[NIMSDK sharedSDK].conversationManager recentSessionBySession:session];
    if (recent)
    {
        NSDictionary *localExt = recent.localExt?:@{};
        NSMutableDictionary *dict = [localExt mutableCopy];
        [dict setObject:@(YES) forKey:NTESRecentSessionAtMark];
        [[NIMSDK sharedSDK].conversationManager updateRecentLocalExt:dict recentSession:recent];
    }
}

Listen to changes of the recent sessions

NIMConversationManagerDelegate provides three callbacks to notify the upper layer of recent conversations:

Callbacks for adding, updating, and deleting a recent session:

objc@protocol NIMConversationManagerDelegate <NSObject>
/**
 *  Callback for adding a recent session
 *
 *  @param recentSession    Recent session
 *  @param totalUnreadCount total unread count
 *  @discussion If a new message is received and the session for the message does not exist in the local storage, the callback will be triggered.
 */
- (void)didAddRecentSession:(NIMRecentSession *)recentSession
           totalUnreadCount:(NSInteger)totalUnreadCount;

/**
 *  Callback for modifying a recent session
 *
 *  @param recentSession    Recent session
 *  @param totalUnreadCount total unread count
 *  @discussion trigger condition includes: 1  If a new message is received and the session for the message does not exist in the local storage, the callback will be triggered.
 * 2. The unread count of the session is cleared.
 * 3. The content of the last message in the session changes. For example, after the message is sent, rectify the sending time as the server time
 * 4. A message is deleted and the deleted message is the last message of the current session.
 */
- (void)didUpdateRecentSession:(NIMRecentSession *)recentSession
              totalUnreadCount:(NSInteger)totalUnreadCount;

/**
 *  Callback for deleting a recent session
 *
 *  @param recentSession    Recent session
 *  @param totalUnreadCount total unread count
 */
- (void)didRemoveRecentSession:(NIMRecentSession *)recentSession
              totalUnreadCount:(NSInteger)totalUnreadCount;

@end

Properties

Parameter Type Description
recentSession NIMRecentSession Recent session
totalUnreadCount NSInteger total unread count.

The callback for changes of unread messages by session type is added.

objc@protocol NIMConversationManagerDelegate <NSObject>

/**
 * Callback forthe unread count (markRead will not use this callback)
 *
 *  @param unreadCountDic The dicationary that contains different types of unread counts.: [@(NIMSessionType): @(messages)]
 */
- (void)didUpdateUnreadCountDic:(NSDictionary *)unreadCountDic;

@end

Unread count

Get the unread count

The unread count for a single NIMRecentSession can be obtained using the unreadCount property in NIMRecentSession.

For the total unread count of all current NIMRecentSessions, the total unread count of messages can be obtained using NIMConversationManager.

objc@protocol NIMConversationManager <NSObject>
/**
 * Get the unread count
 *  @discussion Call the method in the main thread.
 *  @return unread count
 */
- (NSInteger)allUnreadCount;
@end

Unread counts can also be obtained by session type, including P2P, Team, SuperTeam.

objc@protocol NIMConversationManager <NSObject>
/**
 * Get unread counts by SessionType
 * @discussion the method can only be called on the main thread, including conversations that ignore alerts
 * @param type     session type
 *  @return unread count
 */
- (NSInteger)unreadCountOfType:(NIMSessionType)type;
@end

Get the total unread count by the mute state of a session

/**
 * Get all unread counts of recent sessions with or without notification enabled
 *  @param notify enable or disable notifications
 *  @return unread count
 * @discussion Only notify state != NIMTeamNotifyStateNone, notifications are not allowed for groups
 */
- (NSInteger)allUnreadCount:(BOOL)notify;

Get the total unread message list of a specified session type

  • Async interface:
objc@protocol NIMConversationManager <NSObject>
/**
 * Get the total unread message list of a specified session type
 *
 * @param session The specified session
 * @param completion The list of unread messages
 */
- (void)allUnreadMessagesInSession: (NIMSession *)session completion:(NIMFetchMessageHistoryBlock)completion;
@end
  • Sync interface:
objc/**
 * Get the total unread message list of a specified session type
 *
 * @param session The specified session
 * @return The list of unread messages
 */
- (NSArray *)allUnreadMessagesInSession: (NIMSession *)session;

Reset the unread count

When the SDK receives a message, the default message is an unread message, and the unread count is incremented by 1. Because the SDK is completely isolated from the UI, the SDK cannot determine when the message has been read. Therefore, the upper layer must manually call the interface to mark as read according to the UI logic at the appropriate time. The SDK can clear unread data and mark the message status. The corresponding unread count for the most recent session (if any) is automatically set to 0 and the callback for last message modification is triggered.

Clear the unread count as needed. For example, the current session in use does not need to display the unread count, it must be cleared. For non-current sessions, the interface is called only when the user wants to actively clear a specified session or all sessions.

The prototype is divided into two versions with the callback and without the callback.

objc@protocol NIMConversationManager <NSObject>
/**
 *  Mark all messages in a session as read. If you are in the current session chat interface, you need to call this interface every time you receive a message.
 *
 *  @param session target session
 * @discussion async method. Messages will be marked with the set state
 */
- (void)markAllMessagesReadInSession:(NIMSession *)session;

/**
 *  Mark all messages in a session as read
 *
 *  @param session target session
 *  @param session completion callback
 * @discussion async method. Messages will be marked with the set state
 */
- (void)markAllMessagesReadInSession:(NIMSession *)session completion:(NIMSendACKSessionsBlock)completion;
@end

Example

objc//  NIMSessionViewController.m
- (void)onRecvMessages:(NSArray *)messages
{
    ....
    //The session page monitors the callback after receiving a message, and the message is marked read in the current session.
    if ([session isEqual:self.session])
    {
        //Mark read messages only when the message belongs to the current session.
        [[NIMSDK sharedSDK].conversationManager markAllMessagesReadInSession:self.session];
    }
    ....
}

You can also mark all messages in multiple sessions as read. The interface can have a callback optionally.

objective-c@protocol NIMConversationManager <NSObject>

/**
 *  Mark messages in multiple sessions read
 *
 *  @discussion async method call The method does not trigger a callback for updating a recent session, but - onBatchMarkMessagesReadInSessions:
*/
- (void)batchMarkMessagesReadInSessions:(NSArray<NIMSession *> *)sessions;

/**
 *  Mark messages in multiple sessions read
 *
 *  @param completion completion callback If only some of messages are marked read, the NIMBatchSendACKSessionsBlock的error parameter contains the reason for the error and the sessions parameter indicates the sessions where the error ocurrs.
 *  @discussion async method call The method does not trigger a callback for updating a recent session, but - onBatchMarkMessagesReadInSessions:
*/
- (void)batchMarkMessagesReadInSessions:(NSArray<NIMSession *> *)sessions completion:(NIMBatchSendACKSessionsBlock)completion;

@end
  • Mark messages in all recent sessions as read.
objc@protocol NIMConversationManager <NSObject>
/**
 *  Mark all messages in a session as read
 *
 *  @param session target session
 * @discussion async method. The message is marked with the set state.
 */
- (void)markAllMessagesRead;
@end

Mark messages in the recent session as read by session type.

objc@protocol NIMConversationManager <NSObject>
/**
 *  Mark messages in a session as read
 *
 *  @param type Session type
 * @discussion async method. The message is marked with the set state. The method does not trigger a callback for a single recentSession update, but - (void)allMessagesRead.:
 */
- (void)markMessagesReadOfType:(NIMSessionType)type;
@end

Unread count multi-device synchronization

After multi-device synchronization of the unread count is enabled, the message read on one client will also be marked as read on the other devices.

objc@interface NIMSDKConfig : NSObject
/**
 *  Specify whether to sync the unread count on multiple devices
 *
 *  @param session target session
 *  @discussion The default value is NO. If the value is set to YES, multiple devices (PC and mobile) of the same account will get synced with the unread count.
 */
@property (nonatomic, assign) BOOL shouldSyncUnreadCount
@end

Delete recent sessions

Delete recent sessions

The SDK can delete specified recent sessions on the client. However, messages within the session are retained. The current session's unread count is subtracted from the total unread message count.

  • API prototype
objc@protocol NIMConversationManager <NSObject>
/**
 *  Delete a recent session
 *
 *  @param recentSession  Recent session to be deleted
 * @discussion async method to delete a recent session but keep in-session messages
 */
- (void)deleteRecentSession:(NIMRecentSession *)recentSession

/**
*  Delete a recent session
*
*  @param recentSession  Recent session to be deleted
* @param option Specify whether to delete roaming messages. The value of isDeleteRoamMessage is set to NO by default.
*  @param completion Callback for completion. The proxy method didRemoveRecentSession:totalUnreadCount: does not have a callback.
* @discussion async method to delete a recent session but keep in-session messages
*/
- (void)deleteRecentSession:(NIMRecentSession *)recentSession option:(NIMDeleteRecentSessionOption *)option completion:(NIMRemoveRemoteSessionBlock)completion;
@end
  • NIMDeleteRecentSessionOption

Note: The default value of NIMDeleteRecentSessionOption#shouldMarkAllMessagesReadInSessions is false, and the interface without configuration uses a different value

objc@interface NIMDeleteRecentSessionOption : NSObject
/**
 *  Specify whether to delete roaming messages of a chat from the server side.
 *  @discussion. The default value is NO. Only local chats are deleted. If YES,  roaming messages are deleted on the server side.
 */
@property   (nonatomic,assign)  BOOL    isDeleteRoamMessage;

/**
 *  Specify whether to mark all messages in a conversation read
 *  @discussion. The default value is NO. Only local chats are deleted. If YES,  all messages in a chat are marked read
 */
@property   (nonatomic,assign)  BOOL    shouldMarkAllMessagesReadInSessions;
@end

Delete roaming messages

The SDK can delete the roaming messages using the following method:

objc@protocol NIMConversationManager <NSObject>

/**
 *  Delete recent sessions from the server
 *
 * @param sessions List of sessions to be deleted, only NIMSession internally
 *  @param completion Callback for completing the update
 * @discussion After calling this interface successfully, messages before the current session will not roam to other devices
 */
- (void)deleteRemoteSessions:(NSArray<NIMSession *> *)sessions
                  completion:(nullable NIMRemoveRemoteSessionBlock)completion;
                  
@end

Properties

Parameter Type Description
sessions NSArray<NIMSession > List of sessions to be deleted, only including NIMSessions.
completion NIMRemoveRemoteSessionBlock Callback for completion

If you want to delete the message history on the server, see [Delete message history on the server](/en/docs/TM5MzM5Njk/DQ5MTA5ODQ/historical messages?#Delete single-session cloud historical messages).

Was this page helpful?
Yes
No
  • Overview
  • Session
  • Local recent sessions
  • Get recent sessions
  • Get recent sessions
  • Get custom recent sessions
  • API prototype
  • Sample code
  • Get the specified recent sessions
  • Create a recent sessions list
  • Update the recent session list
  • Listen to changes of the recent sessions
  • Unread count
  • Get the unread count
  • Get the total unread count by the mute state of a session
  • Get the total unread message list of a specified session type
  • Reset the unread count
  • Unread count multi-device synchronization
  • Delete recent sessions
  • Delete recent sessions
  • Delete roaming messages