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.

Open channel

An open channel is a Twitch-style public chat where users can easily join without permission. Sendbird Chat SDK now supports two operation systems for open channels, which are classic and dynamic partitioning. These two systems offer the same features and functions, except that dynamic partitioning allows open channels to accommodate a massive number of users.

Open channels can be used in short-lived live events, such as streaming, news-feed type messaging to massive audience, or events that don't require a permanent membership.

Note: To learn about differences between open channels and group channels, see Channel types.


Classic vs. Dynamic partitioning

Classic open channels are the original open channels Sendbird has been providing, and a single classic open channel can handle up to 1,000 participants.

Note: Sendbird applications created before December 15, 2020, are using classic open channels. The classic open channels will be deprecated soon, but the classic channels created up until the deprecation date will remain and function the same way. When the deprecation takes place, all Chat SDK users will be automatically migrated to the new dynamic partitioning system. If you wish to convert to dynamic partitioning open channels beforehand, visit this page and contact us on the Sendbird Dashboard.

On the other hand, dynamic partitioning open channels are designed to accommodate much greater number of users than the classic open channels. The dynamic partitioning open channels can have subchannels where you can divide users evenly.

Learn more about how dynamic partitioning open channel operates in Open channel of our Platform API Docs.


Create a channel

You can create a channel on demand or dynamically through the Chat SDK or the Chat API.

First, configure OpenChannelCreateParams like the following.

let params = OpenChannelCreateParams()
params.name = CHANNEL_NAME
params.operatorUserIds = ops        // Or .operators
params.channelURL = UNIQUE_CHANNEL_URL
params.coverImage = FILE            // Or .coverURL
params.data = DATA
params.customType = CUSTOM_TYPE

OpenChannel.createChannel(params: params, progressHandler: nil) { channel, error in
    guard error == nil else {
        return // Handle error.
    }

    // An open channel with detailed configuration is successfully created.
    let channelURL = channel?.channelURL
}

List of parameters

When creating a channel, you can also append additional information like cover image and description by passing several arguments to the corresponding parameters.

Parameter nameDescription

name

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

coverImage

Type: Data
Uploads a file for the cover image of the channel.

data

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

operatorUserIds

Type: Array
Specifies an array of one or more users to register as operators of the channel. Operators can delete any messages, and also view all messages in the channel without any filtering or throttling.

customType

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

Note: See the Advanced section for more information on cover images and custom types.


Enter a channel

A user must enter an open channel to receive messages. The user can enter up to 10 open channels at once, but the connection is only valid within the current session. When a user who is disconnected from Sendbird server with the disconnect(completionHandler:) method reconnects to the server with the connect(userId:authToken:completionHandler:) method, you should make sure the user re-enters the channels in order to continue receiving messages.

When a user who is already a participant in an open channel moves the app to the background, the user will be disconnected from Sendbird server. But when the user's app returns to the foreground, the Chat SDK will automatically re-enter the user to the participating channel.

Note: When a user is reconnected by attempts of the SendbirdChat instance from a temporary unstable connection, the Chat SDK will automatically re-enter the user to the participating channel.

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

    // Call the instance method of the result object
    // in the openChannel parameter of the callback method.
    openChannel.enter { error in
        guard error == nil else {
            return // Handle error.
        }

        // The current user successfully enters the open channel.
        // By using APIs, the current user can chat with other users in the channel.
    }
}

Exit a channel

If a user exits an open channel, the user can't receive any messages from that channel.

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

    // Call the instance method of the result object
    // in the openChannel parameter of the callback method.
    openChannel.exit { error in
        guard error == nil else {
            return // Handle error.
        }

        // The current user successfully left the open channel.
    }
}

Freeze and unfreeze a channel

An open channel can be freezed only with the Sendbird Dashboard or Chat API as opposed to a group channel which operators of the channel can do that via the Chat SDK.

To freeze a channel, go to Chat > Open channels on the dashboard, select an open channel, and click the Freeze icon at the upper right corner. To unfreeze, select the frozen channel and click the Freeze icon again.

Note : In a frozen channel, only the operators can send a message to the channel and other participants can't chat.


Delete a channel

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

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

openChannel.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 open channels by using the OpenChannelListQuery's loadNextPage(completionHandler:): method which returns a list of OpenChannel objects.

let listQuery = OpenChannel.createOpenChannelListQuery()

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

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

Retrieve a channel by URL

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

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

    // Through the openChannel parameter of the callback method,
    // the open channel object identified with CHANNEL_URL is returned by the Sendbird server,
    // and you can get the channel 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 app, or any 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.


Send a message

To an entered open channel, a user 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 a 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 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 = .users     // Either .users or .channel
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

openChannel.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 the Sendbird server
    // to check your UserMessageCreateParams configuration.
    // The current user can receive messages from other users
    // through the channel(_:didReceive:) 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 a 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 the 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(maxSize: 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
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 = PushNotificationDeliveryOptionDefault

openChannel.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 channel(_:didReceive:) method of an event delegate.
}

If your app goes to the background while uploading a file such as a profile image or picture, the app can complete the uploading process using the application(_:handleEventsForBackgroundURLSession:completionHandler:) method in your AppDelegate. To complete a file upload in progress on the background, a background event delegate should be added and implemented in the AppDelegate. If you don't want to upload a 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 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

openChannel.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

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

Receive messages through a channel delegate

The current user can receive messages sent by other participants through the channel(_:didReceive:) method in channel delegate. A BaseMessage object for each received message is one of the following 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 Chat API

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

class OpenChannelChattingViewController: UIViewController, OpenChannelDelegate {
    func initViewController() {
        SendbirdChat.add(self, identifier: self.delegateIdentifier)
    }

    func channel(_ sender: 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

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

    // A reply to a specific message is successfully sent as a text message.
}

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 // This 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.

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

    // A reply to a specific message is successfully sent as a file message.
}

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 participants in a message

When a participant wants to call the attention of other participants in an open channel where push notifications are not allowed by default, they can mention those participants 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 10 participants 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
params.mentionType = .users

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

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 an open channel. With a returned list, you can display the past messages in your UI once they have loaded.

// There should be one single instance per channel.
let listQuery = openChannel.createPreviousMessageListQuery()
listQuery.customTypeFilter = "greeting"
listQuery.limit = LIMIT
listQuery.reverse = REVERSE

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

List of properties

Property nameDescription

limit

Type: Int
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, it 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 false, it returns a list of messages which the earliest comes at first and the latest at last.

A limit property determines 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 the completionHandler first.


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 an open channel.

Note: The getPreviousMessages() method is deprecated as of August 2021. Accordingly, use the getMessages(timestamp:params:completionHandler:) method instead.

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

openChannel.getMessages(timestamp: TIMESTAMP, params: params) { messages, error in
    guard error == nil else {
        return // 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 MessageTypeFilterAll, MessageTypeFilterUser, MessageTypeFilterFile, and MessageTypeFilterAdmin.

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 an open 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

openChannel.getMessages(messageId: MESSAGE_ID, params: params) { messages, error in
    guard error == nil else {
        return // 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 = openChannel.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_TEXT

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.

includeThreadInfo

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

replyType

Type: ENUM

Specifies the type of message to include in the results.
- NONE (default): Retrieves messages that aren't replies, which include parent messages and non-threaded messages.
- ALL: Retrieves all messages including threaded and non-threaded parent messages as well as its replies.
- ONLY_REPLY_TO_CHANNEL: Retrieves replies that were sent to the channel and their parent messages.

includeParentMessageInfo

Type: bool
Determines whether to include the information of the parent messages in the result. (Default: false)

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.

openChannel.getMessages(timestamp: TIMESTAMP, params: params) { messages, error in
    guard error == nil else {
        return // 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 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.

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

    // 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.includeParentMessageText = INCLUDE_PARENT_MESSAGE_TEXT

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

    // 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

ArgumentDescription

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.

INCLUDE_PARENT_MESSAGE_TEXT

(Deprecated) Type: bool
Determines whether to include the parent message text in the results when the messages are replies in a thread. If the type of the parent message is UserMessage, the value is a message property. If it is FileMessage, the value is the name of the uploaded file.


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 getMessage(params:completionHandler:) method.
BaseMessage.getMessage(params: params) { (message, error) in
    guard error == nil else {
        return // Handle error.
    }

    // 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 the 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.
openChannel.updateUserMessage(messageId: USER_MESSAGE_ID, params: params) { (userMessage, error) in
    guard error == nil else {
        return // Handle error.
    }

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

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

// The FILE_MESSAGE_ID argument below indicates the unique message ID of a FileMessage object to update.
openChannel.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 performed right.
}

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

class OpenChannelChattingViewController: UIViewController, OpenChannelDelegate {
    func initViewController() {
        SendbirdChat.add(self, identifier: self.delegateIdentifier)
    }

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

    }
}

Delete a message

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

// The BASE_MESSAGE argument below indicates a BaseMessage object to delete.
openChannel.deleteMessage(messageId: MESSAGE_ID) { error in
    guard error == nil else {
        return // 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 OpenChannelChattingViewController: UIViewController, OpenChannelDelegate {
    func initViewController() {
        SendbirdChat.add(self, identifier: self.delegateIdentifier)
    }

    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

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

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

File message

openChannel.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

object

Specifies a message to copy.

TARGET_CHANNEL

object

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.


Retrieve a list of participants

You can retrieve a list of participants who are currently online and receiving all messages from an open channel.

let listQuery = openChannel.createParticipantListQuery()

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

Retrieve the latest information on participants

To retrieve the latest and updated information on each online participant in an open channel, you need another ParticipantListQuery instance for the channel. Like the Retrieve a list of participants section above, create a new query instance using the SendbirdChat.createParticipantListQuery() method, and then call its loadNextPage(completionHandler:) method consecutively to retrieve the latest.

You can also retrieve the latest and updated information on users at the application level. Like the Retrieve a list of users section, create a ApplicationUserListQuery instance using the SendbirdChat.createApplicationUserListQuery() method, and then call its loadNextPage(completionHandler:) method consecutively to retrieve the latest.

When retrieving the online (connection) status of a user, by checking connectionStatus of each User object in a returned list, you can get the user's current connection status. connectionStatus has one of the following two values:

ValueDescription

offline

The user isn't connected to Sendbird server.

online

The user is connected to Sendbird server.

Note: If you need to keep track of the connection status of some 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 operators

You can follow the simple implementation below to retrieve a list of operators who monitor and control the activities in an open channel.

OpenChannel.getChannel(url: CHANNEL_URL) { (openChannel, error) in
    guard let openChannel = openChannel, error == nil else {
        return // Handle error.
    }

    // Retrieve operators.
    for operator in openChannel.operators {

    }
}

You can also create a OperatorListQuery instance and use the loadNextPage(completionHandler:) method to retrieve the list like the following.

let listQuery = openChannel.createOperatorListQuery()

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

    // Retrieve operators.
    for operator in users {

    }
}

Register operators

You can register participants as an operator of an open channel.

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

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

Cancel the registration of operators

You can cancel the registration of operators from an open channel but leave them as participants.

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

    // The cancel operation is succeeded,
    // and you could display some message to
    // those who are not operators anymore.
}

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

openChannel.removeAllOperators { (error) in
    guard error == nil else {
        return // Handle error.
    }
}

Retrieve a list of banned or muted users

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

// Retrieve banned users.
let listQuery = openChannel.createBannedUserListQuery()

listQuery.loadNextPage { (users, error) in
    guard error == nil else {
        return // Handle error.
    }
}

// Retrieve muted users.
let listQuery = openChannel.createMutedUserListQuery()

listQuery.loadNextPage { (users, error) in
    guard error == nil else {
        return // Handle error.
    }
}

Ban and unban a user

Operators of an open channel can remove any users that behave inappropriately in the channel through Ba. Banned users are immediately expelled from a channel and allowed to participate in the channel again after the time period set by the operators. Operators can ban and unban users from open channels using the following code.

OpenChannel.getChannel(url: CHANNEL_URL) { (openChannel, error) in
    guard let openChannel = openChannel, error == nil else {
        return // Handle error.
    }

    if openChannel.isOperator(user: SendbirdChat.getCurrentUser()!) {
        // Ban a user.
        openChannel.banUser(USER, seconds: SECONDS, description: DESCRIPTION) { (error) in
            guard error == nil else {
                return // Handle error.
            }

            // The user is successfully banned from the channel.
            // You could notify the user of being banned by displaying a prompt.
        }

        // Unban a user.
        openChannel.unbanUser(USER) { (error) in
            guard error == nil else {
                // Handle error.
            }

            // The user is successfully unbanned for the channel.
            // You could notify the user of being unbanned by displaying a prompt.
        }
    }
}

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


Mute and unmute a user

Operators of an open channel can prohibit selected users from sending messages through Mute. 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 open channels using the following code:

OpenChannel.getChannel(url: CHANNEL_URL) { (openChannel, error) in
    guard let openChannel = openChannel, error == nil else {
        return // Handle error.
    }

    if openChannel.isOperator(user: USER) {
        // Mute a user.
        openChannel.muteUser(USER, seconds: SECONDS, description: DESCRIPTION) { (error) in
            guard error == nil else {
                return // Handle error.
            }

            // The user is successfully muted in the channel.
            // You could notify the user of being muted by displaying a prompt.
        }

        // Unmute a user.
        openChannel.unmuteUser(USER) { (error) in
            guard error == nil else {
                // Handle error.
            }

            // The user is successfully unmuted in the channel.
            // You could notify the user of being unmuted by displaying 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 an open 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.
openChannel.report(message: MESSAGE_TO_REPORT, reportCategory: REPORT_CATEGORY, reportDescription: DESCRIPTION) { (error) in
    guard error == nil else {
        return // Handle error.
    }
}

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

// Report a channel.
openChannel.report(category: REPORT_CATEGORY, reportDescription: DESCRIPTION) { (error) in
    guard error == nil else {
        return // 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.