Chat iOS v4
Chat iOS
Chat
iOS
Home
/
Chat
/
iOS
This is the new Docs for Chat SDK v4 beta for iOS. To see the previous Docs, click here.

Group channel

A group channel is a chat that allows close interactions among a limited number of users. It can be private or public. A private group channel can let a user join the chat through an invitation by another user who is already a member of the chatroom. For 1-to-1 messaging, you can create a private group channel with two members. A public group chat can let a user join the chat without invitation from others. A group channel can consist of one to one hundred members by default setting. This default number of members can increase per request.

A user can receive all messages from the group channels that they are a member of, and sends a message to those channels. They can also receive push notifications, typing indicators, unread counts and read status from the joined channels when they go offline. For more information, see the Push notifications page which describes how to turn on and manage the push preference.


Choose a type of a channel

With our Chat SDK for iOS, you can use a variety of behavior related properties when creating different types of group channels. You can create a group channel after configuring these properties.

Private vs. Public

A private group channel can be joined only by users that have accepted an invitation from an existing channel member by default. On the other hand, a public group channel can be joined by any user without an invitation, like an open channel.

1-to-1 vs. 1-to-N

The isDistinct option determines whether to resume an old channel or to create an entirely new one when someone attempts to open a new channel with a pre-existing member combination. If there is a group channel with those members, the attempt will re-start the existing channel that has their chat history. For example, when attempting to create a new group channel with 3 users, A, B, and C, if a channel with same users already exists, a reference to the existing channel is just returned to who has attempted the new channel.

Consequently, we recommend that you set the isDistinct option to true in 1-to-1 messaging channels to reuse the existing channel when a user directly sends a message to another user. If the option is false, a new group channel is created with the same user even if there is a previous chat between them, and you can't see the old messages or data.

Supergroup vs. Group

For occasions that demand engagement among a high volume of members, you can create a Supergroup channel, an expanded version of a group channel. When the isSuper option is set to true, a Supergroup channel will be created and up to tens of thousands of members can gather in the channel. The maximum number of members in a Supergroup channel varies by your Sendbird plan.

Note: When the isSuper option is set to true, the isDistinct option can't be supported.

Ephemeral vs. Persistent

Messages sent in an ephemeral group channel are not saved in Sendbird's database. As such, old messages that are pushed out of a user's chat view due to new messages can't be retrieved. On the other hand, messages sent in a persistent group channel are stored permanently in the database by default.


Create a channel

A user can create a group channel from inviting other users anytime in their client app. At the implementation level, you just need to write your code which passes the IDs of users to invite as an argument to a parameter in the creation method.

Before you write the code for creating a group channel for a typical 1-to-1 chat, you should make sure that you turn on the isDistinct property of the channel. Otherwise, if you turn off the isDistinct property, a new channel will be created with the same partner user even if there is already an existing channel between them. In this case, multiple 1-to-1 channels between the same two users can exist, each with its own chat history and data.

However, if you plan to create a Supergroup channel, the isDistinct property should be turned false.

Note: If you want to retrieve a list of group channels, which also includes the current user's empty channels without any chat, you should set the includeEmptyChannel option of a GroupChannelListQuery instance to true for the retrieval.

let params = GroupChannelCreateParams()
params.userIds = USER_IDS
params.isDistinct = IS_DISTINCT

GroupChannel.createChannel(params: params) { groupChannel, error in
    guard error == nil else {
        return // Handle error.
    }

    // A group channel with the specified users is successfully created.
    // Through the groupChannel parameter of the callback method,
    // you can get the group channel's data from the result object
    // that the Sendbird server has passed to the callback method.
}

When creating a channel, you can also append additional information like cover image and description by setting properties.

let params = GroupChannelCreateParams()
params.name = NAME
params.userIds = USER_IDS
params.isDistinct = IS_DISTINCT
params.isSuper = IS_SUPER
params.coverURL = COVER_IMAGE_URL
params.data = DATA
params.customType = CUSTOM_TYPE

GroupChannel.createChannel(params: params) { groupChannel, error in
    guard error == nil else {
        return // Handle error.
    }

    // A group channel with additional information is successfully created.
}

List of parameters

Parameter nameDescription

name

Type: String
Specifies the channel topic, or the name of the channel.

isDistinct

Type: bool
Determines whether to reuse an existing channel or create a new channel. If set to true, returns a channel with the same users in USER_IDS or creates a new channel if no match is found. Sendbird server can also use the custom channel type in CUSTOM_TYPE along with USER_IDS to return the corresponding channel. If set to false, Sendbird server always creates a new channel with a combination of the users as well as the channel custom type if specified.

isSuper

Type: bool
Determines whether a new channel will be a Supergroup channel or a group channel. If set to true, the new channel can accommodate more than 2,000 members. When this argument is true, IS_DISTINCT is not supported and should be set to false.

userIds

Type: Array
Specifies a list of one or more IDs of the users to invite to the channel.

coverURL

Type: String
Specifies the cover image URL of the channel.

data

Type: String
Specifies additional channel information such as a long description of the channel or JSON formatted string.

customType

Type: String
Specifies the custom channel type which is used for channel grouping.

You can get a cover image URL using the coverURL property of a GroupChannel object, and update the channel's cover image using update(params:completionHandler)

Note: You can also create a group channel using Chat Platform API which helps you control channel creations and member invitations on your server-side.

Otherwise, you can configure GroupChannelCreateParams and create a new channel with that like below.

var users: [String] = []
users.append("John")
users.append("Harry")
users.append("Jay")

var ops: [String] = []
ops.append("Jeff")

var params = GroupChannelCreateParams()
params.isPublic = false
params.isEphemeral = false
params.isDistinct = false
params.isSuper = false
params.addUserIds(users)
params.operatorUserIds = ops        // Or .operators
params.name = NAME
params.channelURL = UNIQUE_CHANNEL_URL  // In a group channel, you can create a new channel
                                        // by specifying its unique channel URL in a 'GroupChannelCreateParams' object.
params.coverImage = FILE            // Or .coverURL
params.data = DATA
params.customType = CUSTOM_TYPE

GroupChannel.create(params: params) { groupChannel, error in
    guard error == nil else {
        return // Handle error.
    }

    // A group channel with detailed configuration is successfully created.
    // By using groupChannel.channelUrl, groupChannel.members, groupChannel.data,
    // groupChannel.customType, etc., you can access the result object
    // from the Sendbird server to check your GroupChannelCreateParams configuration.
}

Invite users as members

Only members of a group channel can invite new users to the channel. You can also determine whether the newly invited user sees the past messages in the channel or not.

Note: In your dashboard, go to the Settings > Chat > Channels > Group channels, and there is the Chat history option. If the option is turned on, new users can view all messages sent before they have joined the channel. If turned off, new users only see messages sent after they have been invited. By default, this option is turned on.

var userIds: [String] = []
users.append("Tyler")
users.append("Young")

groupChannel.inviteUserIds(userIds) { error in
    guard error == nil else {
        return // Handle error.
    }
}

Accept or decline an invitation from another user

A user who is invited to a group channel can accept or decline the invitation. If a user accepts an invitation, they join the channel as a new member and can start chatting with other members. Otherwise, the invitation will be canceled if a user declines it. Because a user is allowed to join up to 2,000 group channels, the invitation to a user who already belongs to a maximum number of group channels will be canceled automatically.

// Accept an invitation.
groupChannel.acceptInvitation { error in
    guard error == nil else {
        return // Handle error.
    }
}

// Decline an invitation.
groupChannel.declineInvitation { error in
    guard error == nil else {
        return // Handle error.
    }
}

By implementing the channel(_:didReceiveInvitation:inviter:) and channel(_:didDeclineInvitation:inviter:) methods in channel delegate, you can make the client apps of other members in the foreground to be notified of the results of two actions above. If you want more information, see the Event delegate page.

Note: By using the setChannelInvitationPreference(_:completionHandler:) method, you can determine for users within an application whether or not to automatically join a private group channel promptly from an invitation without having to accept it. By default, the value of channel invitation preference is true. If you want to give them the option to decide whether to accept or decline an invitation, you should set the value of the preference to false through setChannelInvitationPreference(_:completionHandler:) like the following sample code.

// The default value of true means that
// a user will automatically join a group channel
// even if the user hasn't accepted the invitation.
var autoAccept = false
SendbirdChat.setChannelInvitationPreference(autoAccept) { error in
    guard error == nil else {
        return // Handle error.
    }
}

Join a channel as a member

Any user can join a public group channel as a member without an invitation and chat with other members in the channel. Since a user is allowed to join up to 2,000 group channels, a user who already belongs to a maximum number of group channels can't join a new channel.

if groupChannel.isPublic {
    groupChannel.join { error in
        guard error == nil else {
            return // Handle error.
        }

        // The current user successfully joins the group channel.
    }
}

Leave a channel

If a user leaves a group channel, the user can't receive messages from the channel anymore.

channel.leave { error in
    guard error == nil else {
        return // Handle error.
    }
}

Freeze and unfreeze a channel

You can temporarily disable various functions of a group channel to stop members from chatting in the channel, and enable the functions so that the members chat with each other. In a frozen channel, only the operators can send a message to the channel and other members can't chat.

// Freeze a channel.
groupChannel.freeze { error in
    guard error == nil else {
        return // Handle error.
    }

    // The channel becomes frozen.
    // You could send a message to announce that
    // chat in the channel is unavailable,
    // or do something in response to a successful operation.
}

// Unfreeze a channel.
groupChannel.unfreeze { error in
    guard error == nil else {
        return // Handle error.
    }

    // The channel becomes unfrozen.
    // You could send a message to announce that
    // chat in the channel is available,
    // or do something in response to a successful operation.
}

Delete a channel

Only the operators of a group channel can delete the channel. Otherwise, an error is returned through completionHandler.

Note: The following code works properly in the operators' client apps only.

groupChannel.delete { error in
    guard error == nil else {
        return // Handle error.
    }

    // The channel is successfully deleted.
}

Retrieve a list of channels

You can retrieve a list of the current user's private group channels using the loadNextPage(completionHandler:) method of a GroupChannelListQuery instance, which returns a list of GroupChannel objects.

Note: Using the includeEmptyChannel option of a GroupChannelListQuery instance, you can determine whether to include empty channels in the result. Empty channels are group channels that have been created but do not contain any messages, and are not included by default. However, if you turn off the Chat history option in your dashboard, you may retrieve empty channels in the result.

let listQuery = GroupChannel.createMyGroupChannelListQuery()
listQuery.includeEmptyChannel = true
listQuery.memberStateFilter = .joinedOnly   // Acceptable values are .all, .joinedOnly, .invitedOnly, .invitedByFriend, .invitedByNonFriend
listQuery.order = GroupChannelListOrderLatestLastMessage    // Acceptable values are .chronological, .latestLastMessage, .channelNameAlphabetical, and .channelMetaDataValueAlphabetical
listQuery.limit = 15

listQuery.loadNextPage { groupChannels, error in
    guard error == nil else {
        return // Handle error.
    }

    // A list of matching group channels is successfully retrieved.
    // Through the groupChannels parameter of the callback method,
    // you can access the data of each group channel from the result list
    // that the Sendbird server has passed to the callback method.
}

You can also retrieve a list of the current user's public group channels using the loadNextPage(completionHandler:) method of a PublicGroupChannelListQuery instance, which returns a list of GroupChannel objects.

Note: Using the includeEmptyChannel option of a PublicGroupChannelListQuery instance, you can determine whether to include empty channels in the result. Empty channels are group channels that have been created but do not contain any messages, and are not included by default. However, if you turn off the Chat history option in your dashboard, you may retrieve empty channels in the result.

let listQuery = GroupChannel.createPublicGroupChannelListQuery()
listQuery.includeEmptyChannel = true
listQuery.publicMembershipFilter = .joined  // Acceptable values are .all, .joined
listQuery.order = .channelNameAlphabetical  // Acceptable values are .chronological, .channelNameAlphabetical, .channelMetaDataValueAlphabetical
listQuery.limit = 15

listQuery.loadNextPage { groupChannels, error in
    guard error == nil else {
        return // Handle error.
    }

    // A list of public group channels matching search criteria is successfully retrieved.
    // Through the groupChannels parameter of the callback method,
    // you can access the data of each group channel from the result list
    // that the Sendbird server has passed to the callback method.
}

Note: Refer to this section on how to search for specific group channels with keywords and filters.


Retrieve a channel by URL

Since a channel URL is a unique identifier of a group channel, you can use a URL when retrieving a channel object.

GroupChannel.getChannel(url: CHANNEL_URL) { groupChannel, error in
    guard error == nil else {
        return // Handle error.
    }

    // Through the groupChannel parameter of the callback method,
    // the group channel object identified with CHANNEL_URL is returned by the Sendbird server,
    // and you can get the group channel's data from the result object.
}

Note: We recommend that you store a user's channel URLs to handle the lifecycle or state changes of your client app, or other unexpected situations. For example, when a user is disconnected from Sendbird server due to switching to another app temporarily, you can provide a smooth restoration of the user's state using a stored URL to fetch the appropriate channel instance.


Hide or archive a channel from a list of channels

The following code will allow you to hide or archive a specific group channel from a list of the channels.

// Hide or archive a group channel.
groupChannel.hide(hidePreviousMessages:IS_HIDE_PREVIOUS_MESSAGES, allowAutoUnhide:IS_ALLOW_AUTO_UNHIDE) { error in
    guard error == nil else {
        return // Handle error.
    }

    // The channel successfully gets hidden from the list.
    // The current user's channel view should be refreshed to reflect the change.
}

// Unhide a group channel.
groupChannel.unhide { error in
    guard error == nil else {
        return // Handle error.
    }

    // The channel successfully gets unhidden from the list.
    // The current user's channel view should be refreshed to reflect the change.
}

List of parameters

Parameter nameDescription

hidePreviousMessages

Type: bool
When the channel gets appeared back in the list, determines whether to conceal the messages sent and received before hiding or archiving the channel. If set to true, the previous messages aren't displayed in the channel. (Default: false)

allowAutoUnhide

Type: bool
Determines the state and operating behavior of the channel in the list. If set to true, the channel is hidden from the list, automatically gets unhidden when receiving a new message from other members, and appears back. If set to false, the channel is archived and disappeared from the list, and never appears back unless unhide(completionHandler:) is called for unarchiving. (Default: true)

Using the channel.hiddenState filter, you can check the channel state with regard to the list.

if channel.hiddenState == .unhidden {
    // Show the channel in the list.
} else if channel.hiddenState == .hiddenAllowAutoUnhide {
    // Hide the channel from the list, and get it appeared back on condition.
} else if channel.hiddenState == .hiddenPreventAutoUnhide {
    // Archive the channel, and get it appeared back in the list only when the unhideChannel() is called.
}

You can also filter channels by their state like the following:

let listQuery = GroupChannel.createMyGroupChannelListQuery()
// The filter options are .unhiddenOnly, .hiddenOnly, .hiddenAllowAutoUnhide, or .hiddenPreventAutoUnhide.
// If set to .hiddenOnly, hidden and archived channels are returned.
listQuery.channelHiddenStateFilter = .hiddenPreventAutoUnhide

listQuery.loadNextPage { groupChannels, error in
    guard error == nil else {
        return // Handle error.
    }

    // Only archived channels are returned in a result list
    // through the groupChannels parameter of the callback method.
}

Filter channels by user IDs

Using the GroupChannelListQuery instance's userIdsExactFilter or userIdsIncludeFilter, you can filter group channels by user IDs. Let's assume the ID of the current user is Harry and the user is a member of two group channels:

  • channelA consists of Harry, John, and Jay.
  • channelB consists of Harry, John, Jay, and Jin.

A userIdsExactFilter returns a list of the current user's group channels containing exactly the queried user IDs. In case you specify only one user ID in the filter, the filter returns a list of the current user's one or more 1-to-1 group channels with the specified user.

let listQuery = GroupChannel.createMyGroupChannelListQuery()
listQuery.userIdsExactFilter = ["John", "Jay"]
listQuery.loadNextPage { groupChannels, error in
    guard error == nil else {
        return // Handle error.
    }

    // Only channelA is returned in a result list through the list parameter of the callback method.
}

A userIdsIncludeFilter filter returns a list of the current user's group channels including the queried user IDs partially and exactly. Two different results can be returned according to the value of the queryType parameter.

let listQuery = GroupChannel.createMyGroupChannelListQuery()
listQuery.setUserIdsIncludeFilter(["John", "Jay"], queryType: .and)
listQuery.loadNextPage { groupChannels, error in
    guard error == nil else {
        return // Handle error.
    }

    // If channelA includes {'John', 'Jay'}, channelB includes {'jay'}, and channelC includes {'Jin'},
    // only channelA is returned.
}

listQuery.setUserIdsIncludeFilter(["John", "Jay"], queryType: .or)
listQuery.loadNextPage { groupChannels, error in
    guard error == nil else {
        return // Handle error.
    }

    // If channelA includes {'John', 'Jay'}, channelB includes {'jay'}, channelC includes {'Jin'},
    // channelA and channelB are returned.
}

Send a message

In a group channel, users can send messages of the following types:

Message typeDescription

UserMessage

A text message sent by a user

FileMessage

A binary file message sent by a user

In addition to these message types, you can further subclassify a message by specifying its custom type. This custom type takes on the form of String and can be used to search or filter messages. It allows you to append information to your message and customize message categorization.

The following code shows several types of parameters that you can configure to customize text messages by using UserMessageCreateParams. Under the UserMessageCreateParams object, you can assign values to message, data and other properties. By assigning arbitrary string to the data property, you can set custom font size, font type or a JSON object. To send your messages, you need to pass the UserMessageCreateParams object as an argument to the parameter in the sendUserMessage(params:completionHandler:) method.

Through completionHandler of the sendUserMessage(params:completionHandler:) method, Sendbird server always notifies whether your message has been successfully sent to the channel. When there is a delivery failure due to network issues, an exception is returned through the callback method.

var params = UserMessageCreateParams()
params.message = MESSAGE
params.customType = CUSTOM_TYPE
params.data = DATA
params.mentionType = MentionTypeUsers       // Acceptable values are MentionTypeUsers and MentionTypeChannel.
params.mentionedUserIds = ["Jeff", "Julia"]     // Or .mentionedUsers = LIST_OF_USERS_TO_MENTION
params.metaArrays = ["itemType": ["tablet"], "quality": ["best", "good"]]   // A key-value pair
params.targetLanguages = ["fr", "de"]           // French and German
params.pushNotificationDeliveryOption = .default

groupChannel.sendUserMessage(params: params) { userMessage, error in
    guard error == nil else {
        return // Handle error.
    }

    // A text message with detailed configuration is successfully sent to the channel.
    // By using userMessage.messageId, userMessage.message, userMessage.customType, and so on,
    // you can access the result object from Sendbird server to check your UserMessageCreateParams configuration.
    // The current user can receive messages from other users
    // through the didReceiveMessage() method of an event delegate.
}

A user can also send binary files through the Chat SDK. The two ways to send a binary file are: sending the file itself, or sending an URL.

Sending a raw file means you're uploading it to Sendbird server where it can be downloaded in client apps. When you upload a file directly to the server, there is a size limit imposed on the file depending on your plan. You can see the limit on your dashboard and adjust it with our sales team.

The other option is to send a file hosted on your server. You can pass the file's URL, which represents its location, as an argument to a parameter. In this case, your file is not hosted on Sendbird server and it can only be downloaded from your own server. When you send a file message with a URL, there is no limit on the file size since it's not directly uploaded to Sendbird server.

Note: You can use sendFileMessages(params:progressHandler:sentMessageHandler:completionHandler:), which is another method that allows you to send up to 20 file messages per one method call. Refer to our API Reference to learn more about it.

The following code shows several types of parameters that you can configure to customize your file messages by using FileMessageCreateParams. Under the FileMessageCreateParams object, you can assign specific values to customType and other properties. To send your messages, you need to pass the FileMessageCreateParams object as an argument to the parameter in the sendFileMessage(params:completionHandler:) method.

Through completionHandler of the sendFileMessage(params:completionHandler:) method, Sendbird server always notifies whether your message has been successfully sent to the channel. When there is a delivery failure due to network issues, an exception is returned through the callback method.

// Send a file message with a raw file.
var thumbnailSizes = [ThumbnailSize]()
thumbnailSizes.append(ThumbnailSize.make(maxCGSize: CGSize(width: 100.0, height: 100.0)))      // 3 thumbnail images are allowed.
thumbnailSizes.append(ThumbnailSize.make(maxWidth: 200.0, maxHeight: 200.0))

var params = FileMessageCreateParams(file: FILE) // Or .fileUrl = FILE_URL. You can also send a file message with a file URL.
params.fileName = FILE_NAME
params.fileSize = FILE_SIZE
params.mimeType = MIME_TYPE
params.thumbnailSizes = thumbnailSizes
params.customType = CUSTOM_TYPE
params.mentionType = .users     // Either .users or .channel
params.mentionedUserIds = ["Jeff", "Julia"]     // Or .mentionedUsers = LIST_OF_USERS_TO_MENTION
params.pushNotificationDeliveryOption = .default

groupChannel.sendFileMessage(params: params) { fileMessage, error in
    guard error == nil else {
        return // Handle error.
    }

    // A file message with detailed configuration is successfully sent to the channel.
    // By using fileMessage.messageId, fileMessage.fileName, fileMessage.customType, and so on,
    // you can access the result object from Sendbird server to check your FileMessageCreateParams configuration.
    // The current user can receive messages from other users
    // through the didReceiveMessage() method of an event delegate.
}

If an app goes to the background while uploading a file such as a profile image or a picture, the app can complete the uploading process by using application(_:handleEventsForBackgroundURLSession:completionHandler:) method in your AppDelegate. To complete the uploading, a background event delegate should be added and implemented in the following delegation. If you don't want to upload the file on the background mode, remove the following delegation in the AppDelegate.

// AppDelegate.swift
class AppDelegate: UIResponder, UIApplicationDelegate {
    func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
        debugPrint("method for handling events for background URL session is waiting to be process. background session id: \(identifier)")
        completionHandler()
    }
}

Send a critical alert message to iOS devices

A critical alert is a notification that can be sent to iOS devices even when mute or Do Not Disturb is turned on. Critical alert messages can be sent to iOS devices through the sendUserMessage(params:completionHandler:) and sendFileMessage(params:completionHandler:) methods. To do so, create an AppleCriticalAlertOptions instance and set it as an attribute of a UserMessageCreateParams instance. Then pass the created UserMessageCreateParams or FileMessageCreateParams instance as an argument to a parameter in the sendUserMessage(params:completionHandler:) or sendFileMessage(params:completionHandler:) method.

Note: To learn more about how to set critical alerts, visit Apple critical alerts.

// Send a critical alert user message.
let userMessageParams = UserMessageCreateParams(message: MESSAGE_TEXT)
let options = AppleCriticalAlertOptions()
options.name = "name"
options.volume = 0.7    // Acceptable values for options.volume are 0 to 1.0, inclusive.
userMessageParams.appleCriticalAlertOptions = options

groupChannel.sendUserMessage(params: userMessageParams) { userMessage, error in
    guard error == nil else {
        return // Handle error.
    }
}

// Send a critical alert file message.
let fileMessageParams = FileMessageCreateParams(file: FILE)
let options = AppleCriticalAlertOptions()
options.name = "name"
options.volume = 0.7    // Acceptable values for options.volume are 0 to 1.0, inclusive.
fileMessageParams.appleCriticalAlertOptions = options

groupChannel.sendFileMessage(params: fileMessageParams) { fileMessage, error in
    guard error == nil else {
        return // Handle error.
    }
}

Receive messages through a channel delegate

Messages sent from other members can be received through the channel(_:didReceive:) method in the channel delegate. A BaseMessage object for each received message is one of the following three message types.

Message typeDescription

UserMessage

A text message sent by a user

FileMessage

A binary file message sent by a user

AdminMessage

A text message sent by an admin through the Platform API

The UNIQUE_DELEGATE_ID argument is a unique identifier to register multiple concurrent delegates.

class GroupChannelChattingViewController: UIViewController, GroupChannelDelegate {
    func initViewController() {
        SendbirdChat.add(self as GroupChannelDelegate, identifier: UNIQUE_DELEGATE_ID)
    }

    func channel(_ channel: BaseChannel, didReceive message: BaseMessage) {
        // You can customize how to display the different types of messages
        // with the result object in the message parameter.
        if message is UserMessage {

        } else if message is FileMessage {

        } else if message is AdminMessage {

        }
    }
}

If the UI isn't valid anymore, remove the channel delegate.

SendbirdChat.removeChannelDelegate(forIdentifier: UNIQUE_DELEGATE_ID)

Reply to a message

You can reply to a specific message in a channel through the sendUserMessage(params:completionHandler:) or sendFileMessage(params:completionHandler:) method. To do so, you should create a UserMessageCreateParams or a FileMessageCreateParams object and then specify the parentMessageId property of the object. Sending reply messages works the same way as sending regular messages to a channel except replies have an additional parentMessageId property.

Reply with a text message

When replying to a message through the sendUserMessage(params:completionHandler:) method, you should specify and pass a UserMessageCreateParams object to the method as a parameter.

// Create a UserMessageCreateParams object.
let params = UserMessageCreateParams(message: MESSAGE_TEXT)
params.parentMessageId = PARENT_MESSAGE_ID

// Pass the params to the parameter in the sendUserMessageWithParams:completionHandler: method.
groupChannel.sendUserMessage(params: params) { message, error in
    guard error == nil else {
        return // Handle error.
    }

    // A reply to a specific message in the form of a text message is successfully sent.
}

List of parameters

Parameter nameDescription

parentMessageId

Type: Int64
Specifies the unique ID of a parent message which has a thread of replies. If the message sent through the sendUserMessage(params:completionHandler:) method is a parent message, the value of this property is 0. If the message is a reply to a parent message, the value is the message ID of the parent message.

Reply with a file message

When replying with a file message through the sendFileMessage(params:completionHandler:) method, you should specify and pass a FileMessageCreateParams object to the method as a parameter.

// Create a FileMessageCreateParams object.
let params = FileMessageCreateParams(file: FILE)
params.parentMessageId = PARENT_MESSAGE_ID

// Pass the params to the parameter in the sendFileMessageWithParams:completionHandler: method.
groupChannel.sendFileMessage(params: params) { message, error in
    guard error == nil else {
        return // Handle error.
    }

    // A reply to a specific message in the form of a file message is successfully sent.
}

List of parameters

Parameter nameDescription

parentMessageId

Type: Int64
Specifies the unique ID of a parent message which has a thread of replies. If the message sent through the sendFileMessage(params:completionHandler:) method is a parent message, the value of this property is 0. If the message is a reply to a parent message, the value is the message ID of the parent message.


Mention other members in a message

When a member wants to call the attention of other members of a group channel, they can mention those members in a message. To do so, you should:

  1. Specify a list of the user IDs to mention.
  2. Add the list to either UserMessageCreateParams or FileMessageCreateParams which may contain options for further action.
  3. Pass the params to either sendUserMessage(params:completionHandler:) or sendFileMessage(params:completionHandler:).
  4. Then only up to ten members mentioned in the message will be notified.
var userIDsToMention: [String] = []
userIDsToMention.append("Harry")
userIDsToMention.append("Jay")
userIDsToMention.append("Jin")

let params = UserMessageCreateParams(message: MESSAGE)
params.mentionedUserIds = userIDsToMention

groupChannel.sendUserMessage(params: params) { userMessage, error in
    guard error == nil else {
        return // Handle error.
    }
}

React to a message

Message reactions will help you build a more engaging chat experience that goes beyond text messages. They are a quick and easy way for users to respond to a message. Users can express their acknowledgement of or feelings about a message without written text by simply adding reactions. They can also view and delete their reactions to the message.

Note: Currently, message reactions are only available in group channels.

let emojiKey = "smile"
// The BASE_MESSAGE argument below indicates an BaseMessage object to add a reaction to.
groupChannel.addReaction(message: BASE_MESSAGE, key: emojiKey) { reactionEvent, error in
    guard error == nil else {
        return // Handle error.
    }
}

// The BASE_MESSAGE argument below indicates an BaseMessage object to delete a reaction from.
groupChannel.deleteReaction(message: BASE_MESSAGE, key: emojiKey) { reactionEvent, error in
    guard error == nil else {
        return // Handle error.
    }
}

// To add or remove an emoji made to the message on the current user's chat view,
// the apply() method should be called in the channel event delegate's updatedReaction() method.

You can decide how to display reactions that were added to messages in the current user’s chat view.

let params = MessageListParams()
params.previousResultSize = 10
params.includeReactions = INCLUDE_REACTIONS

groupChannel.getMessages(timestamp: TIMESTAMP, params: params) { messages, error in
    guard let messages = messages, error == nil else {
        return // Handle error.
    }

    for message in messages {
        for reaction in message.reactions {
            // Check if this emoji has been used when the current user reacted to the message.
            if reaction.userIds.firstIndex(of: SendbirdChat.getCurrentUser()!.userId) != nil {
                let key = reaction.key
                let updatedAt = reaction.updatedAt

                // Show the emoji however you want on the current user's chat view.
            }
        }
    }
}

Note: By using the PreviousMessageListQuery instance's loadPreviousMessagesWithLimit:reverse:completionHandler: method, messages along with their reactions can also be retrieved. To learn more, refer to the Load previous messages section below.

If one of the channel members reacts to a message, the channel:updatedReaction: method in the channel event delegate will be invoked on all channel members’ devices including the one that belongs to the current user. The apply(_:) method will reflect the reaction change to the message in real time.

func channel(_ channel: BaseChannel, updatedReaction reactionEvent: ReactionEvent) {
    // If there is a message with the reactionEvent.messageId,
    // you can apply the reaction change to the message by calling the apply() method.
    message.apply(reactionEvent)

    // Add or remove an emoji made to the message on the current user's chat view.
}

Load previous messages

By using the loadNextPage(completionHandler:) method of a PreviousMessageListQuery instance which returns a list of BaseMessage objects, you can retrieve a set number of previous messages in a group channel. With a returned list, you can display the past messages in your UI once they have loaded.

Note: You can decide whether a user can see the messages sent prior to the user joining a group channel. On your dashboard, go to the Settings > Chat > Channels > Group channels, there is the Chat history option. If turned on, new users are allowed to view a message history in joined group channels. If turned off, new users aren't allowed to see the messages prior to joining a group channel.

// There should be only one single instance per channel.
let listQuery = groupChannel.createPreviousMessageListQuery()
listQuery.includeMetaArray = true   // Retrieve a list of messages along with their metaarrays.
listQuery.includeReactions = true   // Retrieve a list of messages along with their reactions.
listQuery.limit = LIMIT
listQuery.reverse = REVERSE

// Retrieve previous messages.
listQuery.loadNextPage { messages, error in
    guard error == nil else {
        // Handle error.
    }
}

List of properties

Property nameDescription

limit

Type: UInt
Specifies the number of results to return per call. Acceptable values are 1 to 100, inclusive. The recommended value for this parameter is 30.

reverse

Type: bool
Determines whether to sort the retrieved messages in reverse order. If set to true, returns a list of messages which the latest comes at first and the earliest at last. the results are sorted in reverse order. If set to NO, returns a list of messages which the earliest comes at first and the latest at last.

A LIMIT property indicates how many messages to be included in a returned list. A PreviousMessageListQuery instance itself does pagination of a result set according to the value of the LIMIT property, and internally manages a token to retrieve the next page in the result set.

Each time the loadNextPage(completionHandler:) method is called, the instance retrieves a set number of messages in the next page and then updates the token's value to complete the current call and prepare a next call.

If you create a new query instance and call the loadNextPage(completionHandler:) method, a set number of the most recent messages are retrieved because its token has nothing to do with the previously created instance. So we recommend that you create a single query instance and store it as a member variable for traversing through the entire message history.

Note: Before calling the loadNextPage(completionHandler:) method again, you should receive a success callback through completionHandler first.

The following table shows all the supported filters for PreviousMessageListQuery to search for messages you want to retrieve. You can use any filters in a similar fashion with the sample code above.

List of filters

NameFilters

MessageTypeFilter

Messages with the specified message type. Specifying the messageTypeFilter option with a custom message type enables this filter.

CustomTypeFilter

Messages with the specified custom message type. Specifying the customTypeFilter option with a custom message type enables this filter.

SenderUserIdsFilter

Messages that are sent by the specified users. Specifying the channelUserIdsFilter option with an array of user IDs enables this filter.


Load messages by timestamp or message ID

Using the getMessages(timestamp:params:completionHandler:) method, you can retrieve a set number of previous and next messages on both sides of a specific timestamp in a group channel.

The following code shows several types of parameters that you can configure to customize a message query by using MessageListParams. Under the MessageListParams object, you can assign specific values to previousResultSize, messageType, and other properties. To retrieve messages in a channel, you need to pass the MessageListParams object as an argument to the parameter in the getMessages(timestamp:params:completionHandler:) method.

var params = MessageListParams()
params.isInclusive = IS_INCLUSIVE
params.previousResultSize = PREVIOUS_RESULT_SIZE
params.nextResultSize = NEXT_RESULT_SIZE
params.reverse = REVERSE
params.messageType = MESSAGE_TYPE
params.customType = CUSTOM_TYPE

groupChannel.getMessages(timestamp: TIMESTAMP, params: params) { messages, error in
    guard error == nil else {
        // Handle error.
    }

    // A list of previous and next messages on both sides of a specified timestamp
    // is successfully retrieved.
    // Through the messages parameter of the callback method,
    // you can access and display the data of each message from the result list
    // that Sendbird server has passed to the callback method.
}

List of parameters

Parameter nameDescription

timestamp

Type: Int64
Specifies the timestamp to be the reference point of a retrieval, in Unix milliseconds.

isInclusive

Type: bool
Determines whether to include the messages sent exactly on TIMESTAMP.

previousResultSize

Type: Int
Specifies the number of messages to retrieve, which are sent previously before a specified timestamp. Note that the actual number of results may be larger than the set value when there are multiple messages with the same timestamp as the earliest message.

nextResultSize

Type: Int
Specifies the number of messages to retrieve, which are sent later after a specified timestamp. Note that the actual number of results may be larger than the set value when there are multiple messages with the same timestamp as the latest message.

reverse

Type: bool
Determines whether to sort the retrieved messages in reverse order.

messageType

Type: MessageTypeFilter
Specifies the message type to filter the messages with the corresponding type. Acceptable values are .all, .user, .file, and .admin.

customType

Type: String
Specifies the custom message type to filter the messages with the corresponding custom type.

You can also retrieve a set number of previous and next messages on both sides of a specific message ID in a group channel, using the getMessages(messageId:params:completionHandler:) method and MessageListParams object.

var params = MessageListParams()
params.isInclusive = IS_INCLUSIVE
params.previousResultSize = PREVIOUS_RESULT_SIZE
params.nextResultSize = NEXT_RESULT_SIZE
params.reverse = REVERSE
params.messageType = MESSAGE_TYPE
params.customType = CUSTOM_TYPE

groupChannel.getMessages(messageId: MESSAGE_ID, params: params) { messages, error in
    guard error == nil else {
        // Handle error.
    }

    // A list of previous and next messages on both sides of a specified message ID
    // is successfully retrieved.
    // Through the messages parameter of the callback method,
    // you can access and display the data of each message from the result list
    // that Sendbird server has passed to the callback method.
}

List of parameters

Parameter nameDescription

messageId

Type: Int64
Specifies the unique ID of the message to be the reference point of a retrieval.

isInclusive

Type: bool
Determines whether to include the message identified with a specified message ID.

previousResultSize

Type: Int
Specifies the number of messages to retrieve, which are sent previously before a specified message ID.

nextResultSize

Type: Int
Specifies the number of messages to retrieve, which are sent later after a specified timestamp.

reverse

Type: bool
Determines whether to sort the retrieved messages in reverse order.

messageType

Type: MessageTypeFilter
Specifies the message type to filter the messages with the corresponding type. Acceptable values are .all, .user, .file, and .admin.

customType

Type: String
Specifies the custom message type to filter the messages with the corresponding custom type.


List messages along with their replies

The loadNextPage(completionHandler:), getMessages(timestamp:params:completionHandler:) or getMessages(messageId:params:completionHandler:) methods can be used to retrieve messages and their replies in a specific thread.

Load channel messages

The loadNextPage(completionHandler:) method of a PreviousMessageListQuery instance returns a list of BaseMessage objects. With this method, you can retrieve previous messages in a specific channel.

To include the replies of the target messages in the results, change the value of the replyType property set to .all.

let listQuery = groupChannel.createPreviousMessageListQuery()
listQuery.replyType = REPLY_TYPE
listQuery.includeThreadInfo = INCLUDE_THREAD_INFO
listQuery.includeParentMessageInfo = INCLUDE_PARENT_MESSAGE_INFO
listQuery.limit = LIMIT
listQuery.reverse = REVERSE

// This retrieves previous messages.
listQuery.loadNextPage { messages, error in
    guard error == nil else {
        return // Handle error.
    }
}

List of properties

Property nameDescription

limit

Type: UInt
Specifies the number of results to return per call. Acceptable values are 1 to 100, inclusive. The recommended value for this parameter is 30.

reverse

Type: bool
Determines whether to sort the retrieved messages in reverse order. If false, the results are in ascending order.

includeReplies

Type: bool
Determines whether to include replies in the results.

includeThreadInfo

Type: bool
Determines whether to include the thread information of the messages in the results when the results contain parent messages.

includeParentMessageInfo

Type: bool

Determines whether to include the information of the parent messages in the result.

Load messages by timestamp or message ID

The getMessages(timestamp:params:completionHandler:) and getMessages(messageId:params:completionHandler:) methods of a BaseChannel instance return a list of BaseMessage objects.

When using either of the methods above, you can also pass a MessageListParams object as an argument to the parameter in those methods.

let params = MessageListParams()
params.previousResultSize = PREV_RESULT_SIZE
params.nextResultSize = NEXT_RESULT_SIZE
params.isInclusive = INCLUSIVE
params.reverse = REVERSE
params.replyType = REPLY_TYPE
params.includeThreadInfo = INCLUDE_THREAD_INFO
params.includeParentMessageInfo = INCLUDE_PARENT_MESSAGE_INFO

List of parameters

Parameter nameDescription

previousResultSize

Type: Int
Specifies the number of messages to retrieve that were sent before the specified timestamp or message ID.

nextResultSize

Type: Int
Specifies the number of messages to retrieve that were sent after the specified timestamp or message ID.

isInclusive

Type: bool
Determines whether to include the messages with the matching timestamp or message ID in the results.

reverse

Type: bool
Determines whether to sort the retrieved messages in reverse order. If false, the results are in ascending order.

includeReplies

Type: bool
Determines whether to include replies in the results.

includeThreadInfo

Type: bool
Determines whether to include the thread information of the messages in the results when the results contain parent messages.

includeParentMessageInfo

Type: bool

Determines whether to include the information of the parent messages in the result.

By timestamp

The getMessages(timestamp:params:completionHandler:) method returns a set number of messages of previous and next messages on both sides of a specific timestamp in a channel.

groupChannel.getMessages(timestamp: TIMESTAMP, params: params) { messages, error in
    guard error == nil else {
        // Handle error.
        return
    }

    // A list of previous and next messages on both sides of a specified timestamp
    // is successfully retrieved.
    // Through the messages parameter of the callback method,
    // you can access and display the data of each message from the result list
    // that Sendbird server has passed to the callback method.
}

List of parameters

Parameter nameDescription

timestamp

Type: Int64
Specifies the timestamp to be the reference point for messages to retrieve, in Unix milliseconds format. Messages sent before or after the timestamp can be retrieved.

By message ID

The getMessages(messageId:params:completionHandler:) method returns a set number of previous and next messages on both sides of a specific message ID in a channel.

groupChannel.getMessages(messageId: MESSAGE_ID, params: params) { messages, error in
    guard error == nil else {
        // Handle error.
        return
    }

    // A list of previous and next messages on both sides of a specified message ID
    // is successfully retrieved.
    // Through the messages parameter of the callback method,
    // you can access and display the data of each message from the result list
    // that Sendbird server has passed to the callback method.
}

List of parameters

Parameter nameDescription

messageId

Type: Int64
Specifies the message ID to be the reference point for messages to retrieve. Messages sent before or after the message with the matching message ID can be retrieved.


List replies of a parent message

With the timestamp of the parent message, you can retrieve a single message with its replies by creating and passing a ThreadedMessageListParams object into the getThreadedMessages(timestamp:params:completionHandler:) method as an argument.

// Create a ThreadedMessageListParams object.
let params = ThreadedMessageListParams()
params.previousResultSize = PREV_RESULT_SIZE
params.nextResultSize = NEXT_RESULT_SIZE
params.isInclusive = INCLUSIVE
params.reverse = REVERSE
params.includeParentMessageInfo = INCLUDE_PARENT_MESSAGE_INFO

// Pass the params to the parameter in
// the getThreadedMessagesByTimestamp:params:completionHandler: method.
parentMessage.getThreadedMessages(timestamp: TIMESTAMP, params: params) { parentMessage, threadedReplies, error in
    guard error == nil else {
        // Handle error.
        return
    }

    // A list of replies of the specified parent message timestamp
    // is successfully retrieved.
    // Through the threadedReplies parameter of the callback method,
    // you can access and display the data of each message from the result list
    // that Sendbird server has passed to the callback method.
}

List of parameters

Parameter nameDescription

timestamp

Type: Int64
Specifies the timestamp to be the reference point of the retrieval, in Unix milliseconds format.

previousResultSize

Type: Int
Specifies the number of messages to retrieve that were sent before the specified timestamp.

nextResultSize

Type: Int
Specifies the number of messages to retrieve that were sent after the specified timestamp.

isInclusive

Type: bool
Determines whether to include the messages with the matching timestamp in the results.

reverse

Type: bool
Determines whether to sort the retrieved messages in reverse order. If false, the results are in ascending order.

includeParentMessageInfo

Type: bool

Determines whether to include the information of the parent messages in the result.


Retrieve a message

You can retrieve a specific message by creating and passing the MessageRetrievalParams object as an argument into the getMessage(params:completionHandler:) method.

// Create a MessageRetrievalParams object.
let params = MessageRetrievalParams()
params.messageId = MESSAGE_ID
params.channelType = CHANNEL_TYPE
params.channelURL = CHANNEL_URL

// Pass the params to the parameter of the getMessageWithParams:completionHandler: method.
BaseMessage.getMessage(params: params) { (message, error) in
    guard error == nil else {
        // Handle error.
        return
    }

    // The specified message is successfully retrieved.
}

List of parameters

Parameter nameDescription

messageId

Type: Int64
Specifies the unique ID of the message to retrieve.

channelType

Type: ChannelType
Specifies the type of the channel.

channelURL

Type: String
Specifies the URL of the channel to retrieve the message.


Update a message

A user can update any of their own text and file messages sent using UserMessageUpdateParams and FileMessageUpdateParams. An error is returned if a user attempts to update another user's messages. In addition, channel operators can update any messages sent in a channel.

// For a text Message.
var params = UserMessageUpdateParams(message: NEW_TEXT_MESSAGE)
params.customType = NEW_CUSTOM_TYPE
params.data = NEW_DATA

// The USER_MESSAGE_ID argument below indicates the unique message ID of a UserMessage object to update.
groupChannel.updateUserMessage(messageId: USER_MESSAGE_ID, params: params) { userMessage, error in
    guard error == nil else {
        // Handle error.
    }

    // The message is successfully updated.
    // Through the userMessage parameter of the callback method,
    // you could check if the update has been properly applied.
}

// For a file message.
var params = FileMessageUpdateParams()
params.customType = NEW_CUSTOM_TYPE
params.data = NEW_DATA

// The FILE_MESSAGE_ID argument below indicates the unique message ID of a FileMessage object to update.
groupChannel.updateFileMessage(messageId: FILE_MESSAGE_ID, params: params) { fileMessage, error in
    guard error == nil else {
        // Handle error.
    }

    // The message is successfully updated.
    // Through the fileMessage parameter of the callback method,
    // you could check if the update operation has been properly applied.
}

If a message is updated, the channel(_:didUpdate:) method in the channel delegate will be invoked on all channel participants' devices except the one that updated the message.

class GroupChannelChattingViewController: UIViewController, GroupChannelDelegate {
    SendbirdChat.add(self, identifier: self.delegateIdentifier)

    func channel(_ channel: BaseChannel, didUpdate message: BaseMessage) {

    }
}

Delete a message

A user can delete any messages which were sent by themselves. An error is returned if a user attempts to delete the messages of other members. Also channel operators can delete any messages in a channel.

// The BASE_MESSAGE argument below indicates a BaseMessage object to delete.
groupChannel.deleteMessage(messageId: MESSAGE_ID) { error in
    guard error == nil else {
        // Handle error.
    }

    // The message is successfully deleted from the channel.
}

If a message is deleted, the channel(_:messageWasDeleted:) method in channel delegate will be invoked on all channel participants' devices including the one that deleted the message.

class GroupChannelChattingViewController: UIViewController, GroupChannelDelegate {
    func initViewController() {
        SendbirdChat.add(self as GroupChannelDelegate, identifier: UNIQUE_DELEGATE_ID)
    }

    func channel(_ channel: BaseChannel, messageWasDeleted messageId: Int64) {

    }
}

Copy a message

A user can copy and send their own message in the same channel or to another channel.

User message

groupChannel.copyUserMessage(MESSAGE_TO_COPY, toTargetChannel:TARGET_CHANNEL) { userMessage, error in
    guard error == nil else {
        // Handle error.
    }

    // The message is successfully copied to the target channel.
}

File message

groupChannel.copyFileMessage(MESSAGE_TO_COPY, toTargetChannel:TARGET_CHANNEL) { fileMessage, error in
    guard error == nil else {
        return // Handle error.
    }

    // The message is successfully copied to the target channel.
}

List of arguments

ArgumentTypeDescription

MESSAGE_TO_COPY

FileMessage

Specifies a message to copy.

TARGET_CHANNEL

GroupChannel

Specifies a target channel to send a copied message to.

COMPLETION_HANDLER

handler

Specifies the callback handler to receive the response from Sendbird server for a message copy request.


Clear the chat history

By using the resetMyHistory(completionHandler:) method, you can help the current user clear the chat history in a group channel and start a fresh conversation with other members in the same channel. As the method's name implies, the chat history will be cleared only from the channel view of the current user, and will no longer be shown in that view. But the messages aren't deleted from the database of the Sendbird system, and other members can still see all the messages in their channel views.

This method simply clears the messages for the user by updating the lastMessage and messageOffsetTimestamp properties of a group channel object in addition to other internally managed data such as the number of the user’s unread message.

groupChannel.resetMyHistory { error in
    guard error == nil else {
        // Handle error.
    }
}

When a user is online, all data associated with the group channels they are a member of are automatically updated by the SendbirdChat instance. However, when a user is disconnected from Sendbird server and reconnects later, you should call the refresh(completionHandler:) method to update the channels with the latest information.

groupChannel.refresh { error in
    guard error == nil else {
        // Handle error.
    }
}

Note: If you want to make your users see the channels updated to the most recent when their client apps are in the foreground, we recommend you call refresh(completionHandler:) in the didSucceedReconnection() method which receives a callback from Sendbird server when successfully reconnected.


Retrieve a list of all members

You can retrieve a list of members in a group channel using the members property of a GroupChannel object.

let members = groupChannel.members

Members of a group channel are automatically updated when a user is online. But when a user is disconnected from Sendbird server and then reconnected, you should use the refresh(completionHandler:) method to update their channels with the latest information. See the Refresh all data related to a group channel section for the sample code.


Retrieve the online status of members

To stay updated on the online status of each member in a group channel, call the refresh(completionHandler:) method before using the members property of a GroupChannel object to retrieve the members of the channel.

By checking the connectionStatus property of each Member object in the members property, you can then retrieve the user's current connection status. The connectionStatus property has one of the following two values:

ValueDescription

UserConnectionStatus.offline

The user isn't connected to Sendbird server.

UserConnectionStatus.online

The user isn't connected to Sendbird server.

Note: If your client app needs to keep track of the connection status of users in real time, we recommend that you call periodically the loadNextPage(completionHandler:) method of a ApplicationUserListQuery instance after specifying its userIdsFilter filter, perhaps in intervals of one minute or more.


Retrieve a list of members and operators in a specific order

The members and operators of a group channel can be retrieved by using the loadNextPage(completionHandler:) method of a GroupChannelMemberListQuery instance. For a specific order, set either option in the table below to the order property of GroupChannelMemberListQuery.

MemberListOrder

ValueDescription

nicknameAlphabetical

Members are arranged in an alphabetical order (Default).

operatorThenMemberNicknameAlphabetical

Operators are sequenced before the members, both in an alphabetical order.

let listQuery = groupChannel.createOperatorListQuery()
listQuery.limit = 10
listQuery.order = .operatorThenMemberNicknameAlphabetical // In alphabetical order by default

listQuery.loadNextPage { users, error in
    guard let users = users, error == nil else {
        // Handle error.
    }

    // A list of matching members and operators is successfully retrieved.
    // Through the users parameter of the callback method,
    // you can access the data of each item from the result list
    // that Sendbird server has passed to the callback method.
}

GroupChannelOperatorFilter

For filtering, set one of the options in the table below to operatorFilter of GroupChannelMemberListQuery.

ValueDescription

all

No filter is applied to the group channel list (Default).

operator

Only operators are retrieved for the list.

nonOperator

All members, except for operators, are retrieved for the list.

let listQuery = groupChannel.createMemberListQuery()
listQuery.limit = 10
listQuery.operatorFilter = .nonOperator // In alphabetical order by default

listQuery.loadNextPage { users, error in
    guard let users = users, error == nil else {
        // Handle error.
    }

    // A list of matching members and operators is successfully retrieved.
    // Through the users parameter of the callback method,
    // you can access the data of each item from the result list
    // that Sendbird server has passed to the callback method.
}

Retrieve a list of operators

You can create a OperatorListQuery instance and use the loadNextPage(completionHandler:) method to retrieve a list of operators who monitor and control the activities in a group channel.

let listQuery = groupChannel.createOperatorListQuery()
listQuery.loadNextPage { users, error in
    guard let users = users, error == nil else {
        // Handle error.
    }
    // A list of operators is successfully retrieved.
}

Register operators

You can register members as an operator of a group channel.

groupChannel.addOperators(userIds: [USER_ID_1, USER_ID_2]) { error in
    guard error == nil else {
        // Handle error.
    }

    // The members are successfully registered as operators of the channel.
}

Cancel the registration of operators

You can cancel the registration of operators from a group channel but leave them as members.

groupChannel.removeOperators(userIds: [USER_ID_1, USER_ID_2]) { error in
    guard error == nil else {
        // Handle error.
    }

    // The cancel operation is succeeded.
    // You can notify the users of the role change through a prompt.
}

If you want to cancel the registration of all operators in a channel at once, use the following code.

groupChannel.removeAllOperators { error in
    guard error == nil else {
        // Handle error.
    }

    // The cancel operation is succeeded.
    // You can notify the users of the role change through a prompt.
}

Retrieve a list of banned or muted users

You can create a query instance to get a list of banned or muted users from a group channel. This is only available for users who are registered as operators of a group channel.

// Retrieve banned users.
let listQuery = groupChannel.createBannedUserListQuery()
listQuery.loadNextPage { users, error in
    guard let users = users, error == nil else {
        // Handle error.
    }
    // A list of banned users is successfully retrieved.
}

// Retrieve muted users.
let listQuery = groupChannel.createMutedUserListQuery()
listQuery.loadNextPage { users, error in
    guard let users = users, error == nil else {
        // Handle error.
    }
    // A list of members is successfully retrieved.
}

Ban and unban a user

Operators of a group channel can remove any users that behave inappropriately in the channel by using our Ban feature. Banned users are immediately expelled from a channel and allowed to join the channel again after the time period set by the operators. The operators can ban and unban users from group channels using the following code.

GroupChannel.getChannel(url: CHANNEL_URL) { groupChannel, error in
    guard let groupChannel = groupChannel, error == nil else {
        // Handle error.
    }

    if groupChannel.myRole == .operator {
        groupChannel.banUser(USER, seconds: SECONDS, description: DESCRIPTION) { error in
            guard error == nil else {
                // Handle error.
            }

            // The user is successfully banned from the channel.
            // You can notify the user of the ban through a prompt.
        }

        groupChannel.unbanUser(USER) { error in
            guard error == nil else {
                // Handle error.
            }

            // The user is successfully unbanned for the channel.
            // You can notify the user of the unban through a prompt.
        }
    }
}

Note: Instead of banUser(_:seconds:description:completionHandler:) and unbanUser(_:completionHandler:) methods, you can use banUser(userId:seconds:description:completionHandler:) and unbanUser(userId:completionHandler:) as they have the same functionalities.


Mute and unmute a user

Operators of a group channel can prohibit the selected users from sending messages using our Mute feature. Muted users remain in the channel and are allowed to view the messages, but can't send any messages until the operators unmute them. Operators can mute and unmute users in the channel using the following code:

GroupChannel.getChannel(url: CHANNEL_URL) { groupChannel, error in
    guard let groupChannel = groupChannel, error == nil else {
        return
    }

    if groupChannel.myRole == .operator {
        groupChannel.muteUser(USER, seconds: SECONDS, description: DESCRIPTION) { error in
            guard error == nil else {
                // Handle error.
            }

            // The user is successfully muted in the channel.
            // You could notify the user of the mute through a prompt.
        }

        groupChannel.unmuteUser(USER) { error in
            guard error == nil else {
                // Handle error.
            }

            // The user is successfully unmuted in the channel.
            // You could notify the user of the unmute through a prompt.
        }
    }
}

Note: Instead of muteUser(_:seconds:description:completionHandler:) and unmuteUser(_:completionHandler:)methods, you can also use muteUser(userId:seconds:description:completionHandler:) and unmuteUser(userId:completionHandler:), as they have the same functionalities.


Report a message, a user, or a channel

In a group channel, a user can report suspicious or harassing messages as well as the other users who use abusive language. The user can also report channels if there are any inappropriate content or activity within the channel. Based on this feature and our report API, you can build your own in-app system for managing objectionable content and subject.

// Report a message.
groupChannel.report(message: MESSAGE_TO_REPORT, reportCategory: REPORT_CATEGORY, reportDescription: DESCRIPTION) { error in
    guard error == nil else {
        // Handle error.
    }
}

// Report a user.
groupChannel.report(offendingUser: OFFENDING_USER, reportCategory: REPORT_CATEGORY, reportDescription: DESCRIPTION) { error in
    guard error == nil else {
        // Handle error.
    }
}

// Report a channel.
groupChannel.report(category: REPORT_CATEGORY, reportDescription: DESCRIPTION) { error in
    guard error == nil else {
        // Handle error.
    }
}

List of parameters

Parameter nameTypeDescription

message

object

Specifies the message to report for its suspicious, harassing, or inappropriate content.

offendingUser

object

Specifies the user who uses offensive or abusive language such as sending explicit messages or inappropriate comments.

category

enum

Specifies a report category which indicates the reason for reporting. Acceptable values are ReportCategorySuspicious, ReportCategoryHarassing, ReportCategoryInappropriate, and ReportCategorySpam.

reportDescription

string

Specifies additional information to include in the report.