Chat Room
Update time: 2023/02/09 07:58:57
Overview
A chat room is a space where the number of members is unlimited. members can join or leave chat rooms without restrictions. You can create or delete chat rooms by calling corresponding server APIs.
Chat room interface:
objc@interface NIMChatroom : NSObject
/**
* Chat room ID
*/
@property (nullable,nonatomic,copy) NSString *roomId;
/**
* Chat room name
*/
@property (nullable,nonatomic,copy) NSString *name;
/**
* Announcement
*/
@property (nullable,nonatomic,copy) NSString *announcement;
/**
* Creator
*/
@property (nullable,nonatomic,copy) NSString *creator;
/**
* A third-party the extension field. 4000 characters are allowed
*/
@property (nullable,nonatomic,copy) NSString *ext;
/**
* The number of online users
*/
@property (nonatomic,assign) NSInteger onlineUserCount;
/**
* Live streaming URL. To work with live streaming services, you can set the URL of live stream. here
*/
@property (nullable,nonatomic,copy) NSString *broadcastUrl;
/**
* Chat room queue modification level
*/
@property (nonatomic,assign) NIMChatroomQueueModificationLevel queueModificationLevel;
/**
* Check whether all members in the chat room are muted. Onlye administrator can send messages.
*/
- (BOOL)inAllMuteMode;
@end
Join a chat room
To send and receive messages in the chat room, you must join a chat room by calling the interface. Users can join a chat room but cannot invite others to join the chat room. An account can join up to 10 chat rooms simultaneously.
You can join a chat room in independent mode or in non-independent mode.
-
The independent mode allows users to join a chat room without logging in the IM server. The independent mode is suitable for business scenarios that only require the chat room.
-
The non-independent mode requires users to log in the IM server first and join the chat room. It is suitable for scenarios that require IM and chat rooms.
-
You can use the
NIMChatroomIndependentMode
parameter to specify the method for participants to join chat rooms. The default value is the non-independent mode.
objc@protocol NIMChatroomManager <NSObject>
/**
* Join a chat room
*
* @param request request to join a chat room
* @param completion completion callback
*/
- (void)enterChatroom:(NIMChatroomEnterRequest *)request
completion:(NIMChatroomEnterHandler)completion;
@end
NIMChatroomEnterRequest representation
Parameter |
Type |
Description |
---|---|---|
roomId | NSString | Chat room ID |
roomNickname | NSString | room nickname |
roomAvatar | NSString | The avatar of a chat room. You can set an avatar for the chat room. If unspecified, the user info will be used. |
roomExt | NSString | Extension field for the current user in the chat room. The field is valid only for the current session. |
roomNotifyExt | NSString | The extension field of notifications. |
tags | NSString | Login tags. Multiple tags in JsonArray are supported. For example, ["tag1", "tag2"]. |
notifyTargetTags | NSString | Target tags for login and logout notifications. It is a tag expression. See tagCalculator and TagPattern. |
retryCount | NSInteger | The number of reconnection. The default value is 3. If you set the value to 0, the SDK will not reconnect to the server if a connection fails. The setting of your app can be configured based on the business requirements. |
mode | NIMChatroomIndependentMode | The independent login mode. The default value is nil. |
loginAuthType | NIMChatroomLoginAuthType | Authentication type. |
dynamicTokenHandler | NIMProvideChatroomDynamicTokenHandler | Dynamic token callback. |
loginExt | NSString | The extension field |
locationX | NSDecimalNumber | Coordinate X |
locationY | NSDecimalNumber | Coordinate Y |
locationZ | NSDecimalNumber | Coordinate Z |
distance | NSDecimalNumber | Distance of the subscribed message. |
antispamBusinessId | NSString | Additional moderation business ID for certain content. |
Where:
-
Use the parameters for join requests. The extension
roomExt
will be included in each message. This field can be used to add the user's custom information in the chat room, such as permissions and titles. When you sends a message or performs a chat room operation to trigger a notification, this extension information will be placed inNIMMessage - messageExt - roomExt
of the message (messageExt
must be converted toNIMMessageChatroomExtension
). -
Use the parameters for join requests. Other online members of the chat room will receive the notification that the user enters the chat room, and this extension information will be placed in
NIMChatroomNotificationContent - notifyExt
of the notification.
Authentication
The chat room supports three authentication methods using the loginAuthType
field. Default authentication Dynamic token authentication and third-party callback. To apply the dynamic token for authentication, you must set a dynamic token callback using the setChatRoomAuthProvider
method. When joining a chat room, the SDK obtains the token in real time with this callback.
- NIMChatroomLoginAuthType
objctypedef NS_ENUM(NSInteger, NIMChatroomLoginAuthType) {
NIMChatroomLoginAuthTypeDefault = 0,
NIMChatroomLoginAuthTypeDynamicToken = 1,
NIMChatroomLoginAuthTypeThirdPart = 2,
};
- NIMProvideChatroomDynamicTokenHandler
objc/**
* Chat room dynamic token block
*/
typedef NSString*(^NIMProvideChatroomDynamicTokenHandler)(NSString * __nullable roomId, NSString * __nullable account);
Non-independent mode
If you have already logged in to the IM server, you can join a chat room without setting NIMChatroomIndependentMode
.
Independent mode
When joining the chat room in independent mode, you must set the independent mode calling the EnterChatRoomData.setIndependentMode(...)
method.
NIMChatroomIndependentMode representation:
Parameter |
Type |
Description |
---|---|---|
username | NSString | The user name used in the independent mode. If the value is set to nil, the SDK will generate an anonymous account for login. In anonymous mode, NIMChatroomEnterRequest must contain the nickname and avatar. |
token | NSString | Token used in independent mode. A token is invalid if the user name is empty. |
chatroomAppKey | NSString | AppKey, optional. If unspecified, use CommsEase IM AppKey. |
You can get the mode when entering the chat room can be obtained using the following interface:
objc@protocol NIMChatroomManager <NSObject>
/**
* Get the login mode for chat rooms
*/
- (NSInteger)chatroomAuthMode:(NSString *)roomId;
- Anonymous mode and non-anonymous mode
The independent mode can be divided into anonymous mode and non-anonymous mode. The anonymous mode can only receive messagesand cannot send messages.
If NIMChatroomIndependentMode - username
is set to nill, the anonymous mode is used. The SDK will use an automatically generated anonymous account to log in. In anonymous mode, NIMChatRoomEnterRequest
must contain the nickname and avatar.
- Get the URL of a chat room
Since the independent mode does not rely on the connection to the IM server, the SDK cannot automatically obtain the address of the chat room. The client must request the address from the app server and the app server requests the address from the CommsEase server, and then return the request result to the client by the original route. The request path is: `client <-> App server <-> CommsEase server (API: request the address of a chat room.
Register the callback for getting the URL of a chat room:
objc@interface NIMChatroomIndependentMode : NSObject
/**
* Register the callback for getting the URL of a chat room
*
* @param handler method to get the URL of a chat room
* @discussion If a user joins a chat room and refreshing the chat room IP, the SDK will call this callback and pass in the `roomId` and `callback` parameters. The callback requires the upper layer of the application to use `roomId` to make a request to obtain the corresponding address of a chat room and return the address to the SDK using the callback. Note that no matter the request is successful, the callback must return the result. Otherwise, the request to enter the chat room will wait continuously. This interface is only registered once, and later registrations will overwrite the previous registration.
*/
+ (void)registerRequestChatroomAddressesHandler:(NIMRequestChatroomAddressesHandler)handler
@end
Sample code:
objc [NIMChatroomIndependentMode registerRequestChatroomAddressesHandler:^(NSString * _Nonnull roomId, NIMRequestChatroomAddressesCallback _Nonnull callback) {
[YourHTTPService request:roomId completion:^(NSError *error,NSArray *addresses)
{
//The callback must return the result, no matter the request is successful
if(callback)
{
callback(error,addresses);
}
}];
}];
The YourHTTPService
is the interface of the app server, and the app server can call the chat room API of CommsEase to get the specific chat room address.
To join a chat room in independent mode, perform the following steps:
- Set
NIMChatroomIndependentMode
and get the address of the chat room returned in a callback. - Initialize
NIMChatroomEnterRequest
and assign the required values. - Call the method used to join a chat room.
Multi-device login
You can set multi-device login strategy for joining a chat room, specifying whether the same account can join the same chat room at the same time when logging in on different devices. To configure multi-device login, go to the CommsEase console, Application > IM Pro > Features > Chat room > Multi-device login.
- One login session. Only one login is allowed for Windows, Web, Android, and iOS clients.. Only one login is allowed. When the account is successfully logged in on another device, the new login will invalidate the previous login session.
- Unlimited simultaneous logins. All clients of different platforms can log in at the same time. Up to 10 devices can be online at the same time. If you log in on devices within the upper limit of the devices, the prior login sessions on other devices will not be invalidated.
After you modifies the logic of multi-device login policies, the next time a new device logs in, the verification will be performed based on the new multi-device login policies. Devices that have established connections will not be forcibly removed due to the new multi-device login policy.
If a device repeatedly logs in to the same chat room, the later login disconnects the previous persistent connection. At this time, it will invoke a callback for data sync for joining the chat room again, but it will not invoke a callback for data sync for leaving the chat room. For more information about chat room events for data sync (eventType=9), see Chat room events。
Listen to the connection changes of a chat room
Entering the chat room will establish a new connection. Different chat rooms correspond to different connections. You can monitor the connection status and perform some business processing.
objc@protocol NIMChatroomManagerDelegate <NSObject>
/**
* Track the changes of connection status.
*
* @param roomId chat room ID
*@param state indicates the state of current connection
*/
- (void)chatroom:(NSString *)roomId
connectionStateChanged:(NIMChatroomConnectionState)state;
@end
NIMChatroomConnectionState Enumeration
Parameter |
Value | Description |
---|---|---|
NIMChatroomConnectionStateEntering | 0 | Joining a chat room |
NIMChatroomConnectionStateEnterOK | 1 | Joined a chat room |
NIMChatroomConnectionStateEnterFailed | 2 | Failed to join a chat room |
NIMChatroomConnectionStateLoseConnection | 3 | Diconnecting from a chat room. |
If disconnecting from the server, the SDK will automatically reconnect to the server. You do not need to call the interface to join the chat room again.
When the SDK is reconnecting to the server, some special network errors may occur. For example, the user is banned and the chat room status is abnormal). The following callback will be triggered. Make sure the user is redirected to the login interface in the callback.
objc@protocol NIMChatroomManagerDelegate <NSObject>
/**
* Chat room automatic login error
*
* @param roomId chat room ID
* @param error reason for automatic login error
*/
- (void)chatroom:(NSString *)roomId
autoLoginFailed:(NSError *)error;
@end
Listen to being removed
The callback is triggered when a user is removed from a chat room or a chat room is closed:
objc@protocol NIMChatroomManagerDelegate <NSObject>
/**
* Callback for being removed
*
* @param roomId The ID of the chat room from which a user is removed.
* @param result result of being removed
*/
- (void)chatroomBeKicked:(NIMChatroomBeKickedResult *)result;
@end
The result is returned in NIMChatroomBeKickedResult
objc/**
* removed from a chat room
*/
@interface NIMChatroomBeKickedResult : NSObject
/**
* ID of a chat room from which a user is removed
*/
@property (nonatomic, copy) NSString *roomId;
/**
* reason for being removed from a chat room
*/
@property (nonatomic, assign) NIMChatroomKickReason reason;
/**
* extension field for a removed result
*/
@property (nonatomic, copy) NSString *ext;
@end
NIMChatroomKickReason enumeration
Parameter |
Value | Description |
---|---|---|
NIMChatroomKickReasonInvalidRoom | 1 | The chat room has been dismissed. |
NIMChatroomKickReasonByManager | 2 | A participants is removed by the administrator. |
NIMChatroomKickReasonByConflictLogin | 3 | A participant is removed by a login session on another device. |
NIMChatroomKickReasonBlacklist | 5 | A participant is added to the blocklist. |
Leave a chat room
If you leave a chat room, you are disconnected from the chat room and no longer receive messages from the chat room.
objc@protocol NIMChatroomManager <NSObject>
/**
* Leave a chat room
*
* @param roomId chat room ID
* @param completion completion callback
*/
- (void)exitChatroom:(NSString *)roomId
completion:(NIMChatroomHandler)completion;
@end
Properties
Parameter |
Type |
Description |
---|---|---|
roomId | NSString | Chat room ID |
completion | NIMChatroomHandler | Callback for leaving a chat room |
Messaging in chat rooms
The messaging interface of the chat room is the same as the interface of messaging of IM. You can specify the session type as a chat room when sending a message . The session ID is the Chat room ID. Note that the SDK will not persist messages in chat rooms on the local storage.
Parameters:
Parameter |
Type |
Description |
---|---|---|
messageType |
NIMMessageType |
Message type< note type=notice> For a custom message type, pass the body of the custom message to the [messageObject ](https://doc.commsease.com/messaging/api-refer/iOS/doxygen /Latest/zh/d6/df3/interface_n_i_m_message.html#a404cfebf300a3bc3221e0fdf31a8eb7f) field |
session |
NIMSessionType |
Session type, such as, P2P chat, group chat, and chat rooms. |
notifyTargetTags |
NSString * | The tag expression of targets for chat room messages. For more information, see Tag expression. |
locationX |
NSNumber | Coordinate X , used for location messages. |
locationY |
NSNumber | Coordinate Y, used for location messages. |
locationZ |
NSNumber | Coordinate Z , used for location messages. |
toAccIds |
NSArray<NSString*> | List of recipients, used for targeted messages, up to 100 users. |
- To ensure user experience (such as avoiding server overload), two traffic control methods are in place for message receiving. For regular messages, users in chat room can receive up to 20 messages per second, and the excess will be randomly dropped due to traffic control. For high-priority messages, at most 10 messages are received per second. and the excess part cannot be guaranteed not to be lost.
- To avoid losing important messages (server messages), you can set the
HighPriority
parameter in request parameters totrue
to receive server messages with high priority, and ensure that important messages within the upper limit of high-priority message (10 messages per second) are not lost. For more information, see [Send Chat Room Messages](https://doc.commsease.com/docs/TM5MzM5Njk/TYyMDI1MTg?platformId=60353#Send Chat Room Messages).
Update coordinates
objc/**
* Update coordinates
* @param location current coordinates and effective distance
* @param completion completion callback
*/
-(void)updateLocation:(nonnull NIMChatroomLocation *)location
completion:(nullable NIMChatroomHandler)completion;
- NIMChatroomLocation representation
Parameter | Type | Description |
---|---|---|
roomId | NSString | Chat room ID |
locationX | NSNumber | X coordinate |
locationY | NSNumber | Y coordinate |
locationZ | NSNumber | Coordinate Z |
distance | NSNumber | Distance of the subscribed message. |
Notification messages in chat rooms
Some operations in the chat room will generate chat room notification messages. When the following events occur, a notification message will be generated:
NIMChatroomEventType |
Description |
---|---|
NIMChatroomEventTypeEnter = 301 | A participant joins a chat room. |
NIMChatroomEventTypeExit = 302 | A participant leaves a chat room. |
NIMChatroomEventTypeAddBlack = 303 | A participant is added to the blocklist. |
NIMChatroomEventTypeRemoveBlack = 304 | A participant is removed from the blocklist. |
NIMChatroomEventTypeAddMute = 305 | A participant is muted. |
NIMChatroomEventTypeRemoveMute = 306 | A participant is unmuted. |
NIMChatroomEventTypeAddManager = 307 | Assign an administrator |
NIMChatroomEventTypeRemoveManager = 308 | Unassign an administrator |
NIMChatroomEventTypeAddCommon = 309 | Add a permanent participant |
NIMChatroomEventTypeRemoveCommon = 310 | Remove a permanent participant |
NIMChatroomEventTypeClosed = 311 | A chat room is closed |
NIMChatroomEventTypeInfoUpdated = 312 | Update the information about a chat room. |
NIMChatroomEventTypeKicked = 313 | A participant is removed. |
NIMChatroomEventTypeAddMuteTemporarily = 314 | A participant is temporarily muted. |
NIMChatroomEventTypeRemoveMuteTemporarily = 315 | A participant is temporarily unmuted. |
NIMChatroomEventTypeMemberUpdateInfo = 316 | A participant updates the profile information. |
NIMChatroomEventTypeQueueChange = 317 | Notification for common queue changes. |
NIMChatroomEventTypeRoomMuted = 318 | A chat room is muted and only administrators can send messages. All regular participants are muted. |
NIMChatroomEventTypeRoomUnMuted = 319 | A chat room is umuted. |
NIMChatroomEventTypeQueueBatchChange = 320 | Notifications for changes of multiple elements in the queue. |
NIMChatroomEventTypeRecall = 323 | A message is unsent |
NIMChatroomEventTypeQueueBatchAdd = 324 | Multiple elements are added to the queue of a chat room. |
Note that you can also specify whether to send notifications of members entering and leaving the chat room:
- For apps, CommsEase console > select application > message delivery for chat room user entry and exit > enable/disable.
- For a chat room: call the server API to "close the notification of entering and leaving the specified chat room".
- If you want the chat room message history excluding the chat room user's joining and leaving messages, contact the business consultant to apply for closing the "chat room user's joining and leaving message history".
All chat room notifications are wrapped in NIMMessage
. To parse notifications:
-
Check if a message is a notification.
- Check if the
NIMMessage - messageType
field contains the value ofNIMMessageTypeNotification
.
- Check if the
-
Check if a notification belongs to a chat room.
- Cast the type of the
messageObject
field inNIMMessage
toNIMNotificationObject
. - Check if the converted
NIMNotificationObject - notificationType
field contains the value ofNIMNotificationTypeChatroom
.
- Cast the type of the
-
Parse the specific body of a notification.
- Cast the type of the
NIMNotificationObject - content
field toNIMChatroomNotificationContent
.
- Cast the type of the
NIMChatroomNotificationContent
representation:
eventType
: the event type, indicating which event happens in a chat room. The notification type is defined in theNIMChatroomEventType
enumeration.source
: The performer of an event that triggers a notification, indicating who triggers the notification, wrapped asNIMChatroomNotificationMember
type.targets
: The targets of a notification, indicating users that receive the notification inNSArray
. Each element inNSArray
is ofNIMChatroomNotificationMember
type.notifyExt
: The extension field of the notification, defined by each operation interface that triggers the notification. For example,NIMChatroomEnterRequest - roomNotifyExt
ext
: only used for the temporary mute/queue operation event, recording the duration of the mute state, the specific information about queue operations.revokedMessageId
: The ID of an unsent message.revokedMessageTime
: the time when a message is unsent.
The following is an example of parsing the notification for changes of queue elements:
The eventType
of NIMChatroomNotificationContent
, contains two types of events for changes of queue elements, NIMChatroomEventTypeQueueChange
and NIMChatroomEventTypeQueueBatchChange
.
Parse notification messages:
objc- (void)onRecvMessages:(NSArray<NIMMessage *> *)messages
{
for (NIMMessage *message in messages)
{
if (message.messageType == NIMMessageTypeNotification)
{
if (notification.notificationType == NIMNotificationTypeChatroom)
{
NIMChatroomNotificationContent *content = (NIMChatroomNotificationContent *)notification.content;
NSDictionary *info = content.ext;
if (content.eventType == NIMChatroomEventTypeQueueChange)
{
//change type
//NIMChatroomQueueChangeTypeOffer, NIMChatroomQueueChangeTypePoll, NIMChatroomQueueChangeTypeDrop,NIMChatroomQueueChangeTypeUpdate
NIMChatroomQueueChangeType changeType = [[info objectForKey:NIMChatroomEventInfoQueueChangeTypeKey] integerValue];
//key
NSString *key = [info objectForKey:NIMChatroomEventInfoQueueChangeItemKey];
//value
NSString *value = [info objectForKey:NIMChatroomEventInfoQueueChangeItemValueKey];
//deal with key and value
}
if (content.eventType == NIMChatroomEventTypeQueueBatchChange)
{
//change type
//NIMChatroomQueueBatchChangeTypePartClear
NIMChatroomQueueBatchChangeType changeType = [[info objectForKey:NIMChatroomEventInfoQueueChangeTypeKey] integerValue];
NSDictionary *batch = [info objectForKey:NIMChatroomEventInfoQueueChangeItemsKey];
for (NSString *key in batch)
{
NSString *value = [batch objectForKey:key];
//deal with key and value
}
}
}
}
}
}
- The
changeType
parsed inext
in the example
If eventType
of NIMChatroomNotificationContent
is NIMChatroomEventTypeQueueChange
,
The changeType
is NIMChatroomQueueChangeType
:
- NIMChatroomQueueChangeTypeInvalid: invalid or unknown changes
- NIMChatroomQueueChangeTypeOffer: new elements are added
- NIMChatroomQueueChangeTypePoll: get elements
- NIMChatroomQueueChangeTypeDrop: clear elements
- NIMChatroomQueueChangeTypeUpdate: update elements
If eventType
of NIMChatroomNotificationContent
is NIMChatroomEventTypeQueueBatchChange
,
The changeType
is NIMChatroomQueueBatchChangeType
:
- NIMChatroomQueueBatchChangeTypeInvalid: invalid or unknown changes
- Multiple elements in the queue are cleared. If a user gets disconnected, the key associated with the user will be cleared. NIMChatroomQueueBatchChangeTypePartClear
Query message history in the cloud
No offline messages and roaming messages are stored in the chat room. You can query the chat room message history through the interface below. The message histoty in the recent 10 days is stored on the server. However, for files sent 10 days ago (such as images, audio, and video), their urls are still valid (You must manage these urls because these urls cannot be queried wth expired messages). If you need to extend the "chat room history message days", contact a business consultant.
objc@protocol NIMChatroomManager <NSObject>
/**
* Query the chat room message records stored on the server
*
* @param roomId chat room ID
* @param option Search option
*@param result Completion callback
*/
- (void)fetchMessageHistory:(NSString *)roomId
option:(NIMHistoryMessageSearchOption *)option
result:(NIMFetchChatroomHistoryBlock)completion;
@end
NIMHistoryMessageSearchOption parameter list (some fields are invalid for message search, filtered)
>Parameter</ Type |
Description | |
---|---|---|
startTime | NSTimeInterval | The start time of a query. The starting time is required. If unspecified, pass 0. Use the time as the start time to query forward or backward. |
limit | NSUInteger | The number of retrieved entries. The maximum limit is 100 messages |
order | NIMMessageSearchOrder | Query order |
messageTypes | NSArray<NSNumber *> | The type of messages to be queried. The default value is nil, indicating all types of messages are searched. |
Query history messages by tag
You can query message history of a chat room by tag
Query messages between fromTime
and toTime
in seconds, and select the query direction to retrieve the limit
number of messages forward or backward.
objc/**
* Query messages by tag.
* @param param Parameters for queries
*@param completion Completion callback
*/
- (void)getMessagesByTags:(NIMGetMessagesByTagsParam *)param
completion:(nullable NIMGetMessagesByTagsHandler)completion;
NIMGetMessagesByTagsParam
object
Parameter |
Type |
Description |
---|---|---|
roomId | NSInteger | Chat room ID, required. |
tags | NSArray< NSString *> | Tag list, multiple tags to be queried at the same time (required) |
messageTypes | NSArray<NSNumber *> | The type of messages to be queried. Query all types of messages by default. |
fromTime | NSNumber * | The start time of a query in seconds. Convert to the NSTimeInterval type for use. |
toTime | NSNumber * | The end time of a query in seconds. Convert to the NSTimeInterval type for use. |
limit | NSNumber * | The maximum number of messages to be queried. Convert to the NSInteger type for use. |
reverse | NSNumber * | Query direction Convert to the BOOL type for use. |
Sample code:
objc[[NIMSDK sharedSDK].chatroomManager getMessagesByTags:param completion:^(NSError * __nullable error,NSArray<NIMMessage *> * __nullable messages) {
if (error) {
// Failure
} else {
// success
}
}];
Manage chat room information
Get the profile of a chat room
This interface can obtain the list of members in a chat room. The NIM SDK will not cache the list of members. You must cache the data based on your business requirements.
objc@protocol NIMChatroomManager <NSObject>
/**
* Get the chat room info
*
* @param roomId chat room ID
* @param completion completion callback
* @discussion You can get the chat room information only if you have joined the chat room
*/
- (void)fetchChatroomInfo:(NSString *)roomId
completion:(NIMChatroomInfoHandler)completion;
@end
Properties
>Parameter</ Type |
Description | |
---|---|---|
roomId | NSString | Chat room ID |
completion | NIMChatroomInfoHandler | Callback for leaving a chat room |
Edit the profile of a chat room
objc@protocol NIMChatroomManager <NSObject>
/**
* Update the chat room info
*
* @param request request to edit the chat room info
* @param completion completion callback
*/
- (void)updateChatroomInfo:(NIMChatroomUpdateRequest *)request
completion:(nullable NIMChatroomHandler)completion;
@end
NIMChatroomUpdateRequest parameters
Parameter |
Type |
Description |
---|---|---|
roomId | NSString | Chat room ID |
updateInfo | NSDictionary | Information to be updated. The key-value pair {@(NIMChatroomUpdateTag) : NSString or NSNumber} is used. Invalid data will be filtered. |
needNotify | BOOL | Whether notifications will be sent when the profile of a chat room is edited. The default value is NO. |
notifyExt | NSString | The extension field of notifications. |
antispamBusinessId | NSString | Additional moderation business ID for certain content. |
Manage members
Overview
About members
- Members include into two categories: permanent members and temporary members. The permanent member limit is 1000.
- Permanent members include the owner, administrators, regular members, restricted members. Restricted members include members in the blocklist and muted list.
- Except for the creator, when other members join a chat room, they are all guests by default.
- If a guest is assigned admin and then unassign administrator, it becomes a regular member (not a guest).
- In the chat rooms, to turn an administrator to regular member, you can revoke the administrator role. You cannot set admin as regular member.
- Only the creator can manage administrators. Administrators have no permission to manage the creator.
- Regular members become guest after being revoked.
- If a guest is added to the blocklist, the guest becomes a permanent member and is disconnected by the server and cannot join the chat room unless the member is removed from the blocklist. After being removed the blacklist, a permanent member becomes a guest.
- After being permanently muted, the role becomes a permanent member. After being permanently unmuted, the role becomes a guest. After being permanently unmuted, the expiration time of the temporary mute will not be affected.
- Temporary muting or unmuting members does not change the role. If you repeatedly muting a member, the later mute will overwrite the expiration time of the previous mute.
- Guests are temporary members of the chat room. Guests does not belong to any chat rooms.
ChatRoomMember interface
objc/**
* Chat room member
*/
@interface NIMChatroomMember : NSObject
/**
* User ID
*/
@property (nullable,nonatomic,copy) NSString *userId;
/**
* Nickname in a chat room. The nickname is specified when the user joins the chat room
*/
@property (nullable,nonatomic,copy) NSString *roomNickname;
/**
* The avatar in the chat room specified by the user when joining the chat room.
*/
@property (nullable,nonatomic,copy) NSString *roomAvatar;
/**
* Thumbnail of an avatar in a chat room
* @discussion only applicable to resources uploaded using CommsEase upload service. Otherwise the parameter will be invalid.
*/
@property (nullable,nonatomic,copy,readonly) NSString *roomAvatarThumbnail;
/**
* Extension field reserved for developers specified when a user joins a chat room.
*/
@property (nullable,nonatomic,copy) NSString *roomExt;
/**
* Member type
*/
@property (nonatomic,assign) NIMChatroomMemberType type;
/**
* Check if mute is applied
*/
@property (nonatomic,assign) BOOL isMuted;
/**
* Check for temporary mute
* @discussion Temporary mute is unrelated to the mute property
*/
@property (nonatomic,assign) BOOL isTempMuted;
/**
* Remaining period for temporary mute
*/
@property (nonatomic,assign) unsigned long long tempMuteDuration;
/**
* Check if a user is included in a blacklist
*/
@property (nonatomic,assign) BOOL isInBlackList;
/**
* Check if a user is online. Only special members can stay offline. Guests have only online status.
*/
@property (nonatomic,assign) BOOL isOnline;
/**
* Time a user joined a chat room
*/
@property (nonatomic,assign) NSTimeInterval enterTimeInterval;
/**
* Member tags
*/
@property (nullable,nonatomic,copy) NSString *tags;
/**
* notifyTargetTags of members
*/
@property (nullable,nonatomic,copy) NSString *notifyTargetTags;
@end
Get the members in a chat room
This interface can obtain the list of members. The NIM SDK will not cache the list of members. You must cache the data based on your business requirements.
Get the members in a chat room in pagination
objc@protocol NIMChatroomManager <NSObject>
/**
* Get members in a chat room
*
* @param request request to get the members
* @param completion callback for completion
*/
- (void)fetchChatroomMembers:(NIMChatroomMemberRequest *)request
completion:(NIMChatroomMembersHandler)completion;
@end
NIMChatroomMemberRequest parameters
>Parameter</ Type |
Description | |
---|---|---|
roomId | NSString | Chat room ID |
type | NIMChatroomFetchMemberType | The participant type. |
lastMember | NIMChatroomMember | The anchor member excluded. * A value of nil starts the query from the current time or from the first page. |
limit | NSUInteger | Get the number of participants |
NIMChatroomFetchMemberType
Parameter |
Description |
---|---|
NIMChatroomFetchMemberTypeRegular | Regular participant |
NIMChatroomFetchMemberTypeTemp | Temporary participant |
NIMChatroomFetchMemberTypeRegularOnline | Online regular participants |
NIMChatroomFetchMemberTypeUnRegularReversedOrder | Non-regular participants |
Get the specified members in chat rooms
objc@protocol NIMChatroomManager <NSObject>
/**
* Get member profiles based on user IDs
*
* @param request request to get the members
* @param completion callback for completion
*/
- (void)fetchChatroomMembersByIds:(NIMChatroomMembersByIdsRequest *)request
completion:(NIMChatroomMembersHandler)completion;
@end
NIMChatroomMembersByIdsRequest parameters
>Parameter</ Type |
Description | |
---|---|---|
roomId | NSString | Chat room ID |
userIds | NSArray<NSString *> | The list of user IDs. up to 20 IDs are allowed. |
Edit the profile of the current user
objc@protocol NIMChatroomManager <NSObject>
/**
* Update the profile of the current user in a chat room.
*/
- (void)updateMyChatroomMemberInfo:(NIMChatroomMemberInfoUpdateRequest *)request
completion:(nullable NIMChatroomHandler)completion;
@end
NIMChatroomMemberInfoUpdateRequest parameter
objc/**
* Request to update user profiles in a chat room
*/
@interface NIMChatroomMemberInfoUpdateRequest : NSObject
/**
* Chat room ID
*/
@property (nonatomic,copy) NSString *roomId;
/**
* Information to be updated. The key-value pair {@(NIMChatroomMemberInfoUpdateTag) : NSString} is passed in. Invalid data will be filtered.
*/
@property (nonatomic,copy) NSDictionary *updateInfo;
/**
* Specify whether to send notifications.
*/
@property (nonatomic,assign) BOOL needNotify;
/**
* Extension for event notifications
*/
@property (nullable,nonatomic,copy) NSString *notifyExt;
/**
* Specify whether to persist the updated information. The setting is applied for members. The default value is NO
*/
@property (nonatomic,assign) BOOL needSave;
/**
* Business for anti-spam
*/
@property (nonatomic,strong) NSString *antispamBusinessId;
@end
Example:
objcNIMChatroomMemberInfoUpdateRequest *request = [[NIMChatroomMemberInfoUpdateRequest alloc] init];
request.roomId = @"123";
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
[dic setValue:@"zhangsan" forKey:@(NIMChatroomMemberInfoUpdateTagNick)];
request.updateInfo = dic;
[[NIMSDK sharedSDK].chatroomManager updateMyChatroomMemberInfo:request
completion:^(NSError * _Nullable error) { }];
After calling this interface, you must modify the member object of in the memory cache.
Add or remove admins
objc@protocol NIMChatroomManager <NSObject>
/**
* Assign or unassign administrators
*
* @param request request to update the role
* @param completion completion callback
*/
- (void)markMemberManager:(NIMChatroomMemberUpdateRequest *)request
completion:(NIMChatroomHandler)completion;
@end
Set whether to add or remove with NIMChatroomMemberUpdateRequest - enable
.
Assign or revoke membership of a user
objc@protocol NIMChatroomManager <NSObject>
/**
* Add or remove regular members
*
* @param request request to update the role
* @param completion completion callback
*/
- (void)markNormalMember:(NIMChatroomMemberUpdateRequest *)request
completion:(NIMChatroomHandler)completion;
@end
Set whether to add or remove with NIMChatroomMemberUpdateRequest - enable
.
Add to or remove from the blocklist
objc@protocol NIMChatroomManager <NSObject>
/**
* Update the blacklist in a chat room
*
* @param request request to update the role
* @param completion completion callback
*/
- (void)updateMemberBlack:(NIMChatroomMemberUpdateRequest *)request
completion:(NIMChatroomHandler)completion;
@end
Set whether to add or remove with NIMChatroomMemberUpdateRequest - enable
.
Mute or unmute members
objc@protocol NIMChatroomManager <NSObject>
/**
* Update the list of muted members in a chat room
*
* @param request request to update the role
* @param completion completion callback
*/
- (void)updateMemberMute:(NIMChatroomMemberUpdateRequest *)request
completion:(NIMChatroomHandler)completion;
@end
Set whether to add or remove with NIMChatroomMemberUpdateRequest - enable
.
Remove a specified member
Creators or administrators can remove regular members with lower privileges from a chat room.
objc@protocol NIMChatroomManager <NSObject>
/**
* Remove a specified member from a chat room
*
* @param request request to remove a specified member from the chat room
* @param completion completion callback
*/
- (void)kickMember:(NIMChatroomMemberKickRequest *)request
completion:(NIMChatroomHandler)completion;
@end
NIMChatroomMemberKickRequest parameters
Parameter | Type | Description |
---|---|---|
roomId | NSString | Chat room ID |
userId | NSString | User ID. Only administrators can remove regular members. Only the owner can remove administrators |
notifyExt | NSString | The extension field of notifications for being removed from a chat room. |
Temporarily mute a member
objc@protocol NIMChatroomManager <NSObject>
/**
* Update the list of temporarily muted members in a chat room
*
* @param request request to update the role
* @param duration duration of a mute state in seconds
* @param completion completion callback
*/
- (void)updateMemberTempMute:(NIMChatroomMemberUpdateRequest *)request
duration:(unsigned long long)duration
completion:(nullable NIMChatroomHandler)completion;
@end
Chat room queue
Chat room queue is provided for seat management in interactive live streaming. Permissions are determined by NIMChatroom - queueModificationLevel
and can be modified by updateChatroomInfo
. By default, all users can call the interface to modify the queue content.
Get the chat room queue
objc@protocol NIMChatroomManager <NSObject>
/**
* Get the chat room queue
*
* @param roomId chat room ID
* @param completion completion callback
*/
- (void)fetchChatroomQueue:(NSString *)roomId
completion:(nullable NIMChatroomQueueInfoHandler)completion;
@end
Example
objcNSString *roomId = @"your_room_id";
[[NIMSDK sharedSDK].chatroomManager fetchChatroomQueue:roomId
completion:^(NSError * _Nullable error, NSArray<NSDictionary<NSString *,NSString *> *> * _Nullable info) {
if (!error)
{
//deal with info
}
else
{
//deal with error
}
}];
Add or update elements
If the element added by User A is updated by User B, the owner of the element is User B.
objc@protocol NIMChatroomManager <NSObject>
/**
* Add or update common queue elements in a chat room. The permission is granted by the queueModificationLevel of NIMChatroom.
*
* @param request Queue request to a chat room
* @param completion completion callback
*/
- (void)updateChatroomQueueObject:(NIMChatroomQueueUpdateRequest *)request
completion:(nullable NIMChatroomHandler)completion;
@end
NIMChatroomQueueUpdateRequest parameters
>Parameter</ Type |
Description | |
---|---|---|
roomId | NSString | Chat room ID |
key | NSString | Update the key of an element. If the key already exists, update the value of the key. If the key does not exist, append the element. 32 bytes are supported. |
value | NSString | Update the value of a new element. 4096 bytes are allowed |
transient | BOOL | Whether an element is deleted when a user that adds the element gets disconnected or leaves a chat room, The default value is false, indicating that the element is not deleted.. If the value is set to YES, the notification NIMChatroomEventTypeQueueBatchChange for changes of multiple elements in a queue is sent |
elementAccid | NSString | accounts to which an element belongs. No argument is taken by default. The element belongs to the current user. Administrators can assign specified elements to other valid accounts. |
Example
objcNIMChatroomQueueUpdateRequest *request = [[NIMChatroomQueueUpdateRequest alloc] init];
request.roomId = @"your_room_id";
request.key = @"key";
request.value = @"value";
request.transient = YES;
req.element_accid_ = UTF8(request.elementAccid);
[[NIMSDK sharedSDK].chatroomManager updateChatroomQueueObject:request
completion:^(NSError * _Nullable error) {
if (!error)
{
//deal with success
}
else
{
//deal with error
}
}];
Update multiple elements in a chat room queue
If the element added by User A is updated by User B, the owner of the element is User B.
objc@protocol NIMChatroomManager <NSObject>
/**
* Update multiple common queue elements in a chat room. The permission is granted by the queueModificationLevel of NIMChatroom
*
* @param request Multiple requests to update the chat room queue
* @param completion completion callback
*/
- (void)batchUpdateChatroomQueueObject:(NIMChatroomQueueBatchUpdateRequest *)request
completion:(nullable NIMChatroomQueueBatchUpdateHandler)completion;
@end
NIMChatroomQueueBatchUpdateRequest parameters
Parameter |
Type |
Description |
---|---|---|
roomId | NSString | Chat room ID |
elements | NSDictionary | Update multiple key-value pairs of elements. The key and value are represented with elementKey and elementValue. elementKey can contain up to 128 bytes, and elementValue 4096 bytes. A maximum of 100 key-value pairs can be updated at a time. |
needNotify | BOOL | Whether broadcast notifications are sent. |
notifyExt | NSString | The extension field of notifications, up to 2,048 bytes. |
Example
objcNIMChatroomQueueBatchUpdateRequest *request = [[NIMChatroomQueueBatchUpdateRequest alloc] init];
request.roomId = @"your_room_id";
request.needNotify = YES;
request.notifyExt = @" received a notification";
request.elements = dict;
[[NIMSDK sharedSDK].chatroomManager batchUpdateChatroomQueueObject:request completion:^(NSError * _Nullable error, NSArray<NSString *> * _Nullable elements) {
if (!error)
{
//deal with success
}
else
{
//deal with error
}
}];
Remove a specified element
objc@protocol NIMChatroomManager <NSObject>
/**
* Remove queue elements in a chat room. The permission is granted by the queueModificationLevel of NIMChatroom
*
* @param request request to get queue elements
* @param completion completion callback
*/
- (void)removeChatroomQueueObject:(NIMChatroomQueueRemoveRequest *)request
completion:(nullable NIMChatroomQueueRemoveHandler)completion;
@end
NIMChatroomQueueRemoveRequest parameters
Parameter | Type | Description |
---|---|---|
roomId | NSString | Chat room ID |
key | NSString | The key of a specified element. For the first element, pass nil. |
Example
objcNIMChatroomQueueRemoveRequest *request = [[NIMChatroomQueueRemoveRequest alloc] init];
request.roomId = @"your_room_id";
request.key = @"key";
[[NIMSDK sharedSDK].chatroomManager removeChatroomQueueObject:request completion:^(NSError * _Nullable error, NSDictionary<NSString *,NSString *> * _Nullable element) {
if (!error)
{
//deal with removed element
}
else
{
//deal with error
}
}];
Delete a queue
objc@protocol NIMChatroomManager <NSObject>
/**
* Delete the queue in a chat room. The permission is granted by the queueModificationLevel of NIMChatroom
*
* @param roomId chat room ID
* @param completion completion callback
*/
- (void)dropChatroomQueue:(NSString *)roomId
completion:(nullable NIMChatroomHandler)completion;
@end
Example
objcNSString *roomId = @"your_room_id";
[[NIMSDK sharedSDK].chatroomManager dropChatroomQueue:roomId completion:^(NSError * _Nullable error) {
if (!error)
{
//deal with success
}
else
{
//deal with error
}
}];
Tags
Listener for the tag changes
When a tag is modified, a callback will be called including the chat room ID of the changed tag and the tag.
java/**
* Notification for editing tags
* @param event The event for a notification
*/
- (void)tagsUpdate:(NIMChatroomTagsUpdateEvent *)event;
App users can update the tags at any time.
objc/**
* Update tags
* @param tags tags
* @param completion completion callback
*/
-(void)updateTags:(nonnull NIMChatroomTagsUpdate *)tags
completion:(nullable NIMChatroomHandler)completion;
- NIMChatroomTagsUpdate parameters
>Parameter</ Type |
Description | |
---|---|---|
roomId | NSString | Chat room ID |
tags | NSArray |
Tags, you can set multiple tags. If unspecified, the old tags will be deleted. |
notifyTargetTags | NSString | The target tag of the notification for updating tags is a tag expression. The targets of notifications are also changed when the user is disconnected. See TagCalculator and TagPattern. If unspecified, the old notifyTargetTags will be deleted. |
needNotify | BOOL | Whether a notification is required. A value of true will generate a notification of 325 type. |
ext | NSString | The extension field of a notification. |