Channels
Our channels enable developers to implement different types of chat messaging capabilities into their applications easily
Users can create and join channels where they will be able to participate and chat with other users. A channel can support up to 300,000 members and can contain an unlimited number of messages. Any message exchanged in the channels will be pushed to all other members of the channel in real-time.

Channel Model

When you are observing channels, it will always appear in this format.
1
{
2
"channelId": "string",
3
"isDistinct": true,
4
"metadata": {},
5
"type": "standard",
6
"tags": [
7
"string"
8
],
9
"isMuted": true,
10
"isRateLimited": true,
11
"rateLimit": 0,
12
"displayName": "string",
13
"memberCount": 0,
14
"messageCount": 0,
15
"lastActivity": "2021-08-26T06:05:25.996Z",
16
"createdAt": "2021-08-26T06:05:25.996Z",
17
"updatedAt": "2021-08-26T06:05:25.996Z",
18
"avatarFileId": "string"
19
}
Copied!

Channel Description

Name
Data Type
Description
Attributes
channelId
String
ID of the channel
isDistinct
Boolean
Is channel distinct?
metadata
Object
Additional properties to support custom fields
type
String
Type of channel
Enum:[standard, private, conversation, broadcast, community, live]
tags
Array.<String>
Tags used for searching
isMuted
Boolean
Is this channel muted?
Computed by using muteTimeout
isRateLimited
Boolean
This channel has limited sending rate?
Computed by using muteTimeout
rateLimit
Integer
Number of messages within rate limit
displayName
String
Channel name for displaying
memberCount
Integer
Number of members in channel
messageCount
Integer
Number of messages in channel
lastActivity
string($date-time)
Date/time of user's last activity related to the channel (E.g. add/remove member)
createdAt
string($date-time)
Date/time the channel was created
updatedAt
string($date-time)
Date/time the channel was last updated
avatarFileId
String
Avatar file ID

Channel Types

Amity's Chat SDK supports the creations of 4 types of chat channels. Each type is designed to match a particular use-case for chat channels. Here's a table showing what features each channel offers:
Channel Type
Discoverable by
Message sending privileges
Moderation access
Community
All users and admins
Users and admins
All Moderation tools
Live
Only members and admins
Users and admins
All Moderation tools
Broadcast
All users and admins
Admins
Admin Moderation tools
Conversation
Only members
Users
No Moderation tools

Community

All community channels are visible on the Amity Social Cloud Console.

The community channel is our default channel type and can be discovered by all users and admins. It acts as a public chat channel that showcases all of the features that our SDK's have to offer.
Typical use cases:
    Team collaboration
    Online gaming
    Celebrity fan club
    Live streaming
    Any type of public chat

Live

All live channels are visible on the Amity Social Cloud Console.

Live channels offer the ability for users and admins to create channels with exclusive memberships. The live channel is identical to our Community channel in features with the caveat that users will not be able to discover the channel when querying for all channels unless they are already a member of it. However, users and admins can still invite other users to join the channel.
Typical use cases:
    Healthcare
    Project Discussion
    Any type of private chat
Community and Live channel types can use our SDK moderation tools:
    Message and user flagging
    Muting/Unmuting users
    Banning/Unbanning users from channel
    Profanity filters
    Whitelisted URLs
    User rate-limiting

Broadcast

All broadcast channels are visible on the Amity Social Cloud Console.
The Broadcast channel is heavily adopted by corporate users who constantly promote or advertise their products, or make the announcement to drive awareness. Unlike other channel types, broadcast channels only allow admin users to send messages from Console, and everyone else in the channel will be under read-only mode.
Since this is a one-way communication channel, tailored moderation tools are provided as well, for instance, users won't be able to flag message/user in the channel.
Typical use cases:
    Marketing & Advertising
    School / Government Announcements

Conversation

Conversation channels are NOT visible on the Amity Social Cloud Console.
The Conversation channel is our solution to 1-on-1 messaging. Unlike the other channel types, a Conversation channel can be created simply by knowing the userId of the user we want to converse with. Users can start conversations with any other user and only they will be able to see their conversation.
There are no moderation tools for Conversation channels, users will be able to converse freely with no oversight!
Typical use cases:
    Hospitality
    Financial Consultancy
    Customer Support
Since this is similar to 1-on-1 messaging, Conversation channels have some limitations. The following are not allowed:
    Join and leave channel
    Ban and unban channel members
    Add and remove channel members
Channel types can be created through SDK i.e Community, Live and Conversation. Creation of Private and Standard type has been removed. Creation of Broadcast channel type is not supported through the SDK. But for query, getChannels: method supports all channel types including Broadcast, Private and Standard.

Channel Members

When a user joins a channel, they are able to observe and chat with other users in that channel. They are also automatically considered a member of that channel. The Chat SDK provides the ability to view which users are currently in the channel as well as invite other users to join the channel.
Each channel is identified by a unique channelId, which is any string that uniquely identifies the channel and is immutable through its lifetime. When creating channels, you can specify your own channelId, or leave it to Amity's Chat SDK to automatically generate one for you.
It's important to note that, createChannel: guarantees that the requested channel is a new channel, whereas joinChannel: will attempt to join an existing channel. If there is a requirement to create a new channel, then use of createChannel: then call joinChannel:. Lastly calling getChannel: only gives you back the channel LiveObject, but it won't make the current user join said channel.
Channel management methods are contained in a AmityChannelRepository class. Before being able to call any channel method, you must initialize a repository instance using the AmityClient instance you created during setup:
1
let channelRepository = AmityChannelRepository(client: client)
Copied!

Create Channel

AmityChannelRepository provides createChannel() method to create a new channel. It supports creating of 3 types of channels Community, Live and Conversation. Each channel type has specific builder classes which help you to create that particular channel. Build your channel information first and then create the particular channel.
1
var channelToken: AmityNotificationToken?
2
3
...
4
5
let builder = AmityCommunityChannelBuilder()
6
7
// Optional. If you don't provide channel id, sdk will create a unique channel id for you.
8
builder.setId("my-id")
9
10
builder.setUserIds(userIds)
11
builder.setDisplayName("my-community-channel_\(randomId)")
12
builder.setTags(["ch-comm","ios-sdk"])
13
builder.setMetadata(["sdk_type":"ios"])
14
15
channelObject = channelRepository.createChannel().community(with: builder)
16
channelToken = channelObject.observe { channelObject, error in
17
// Do Something
18
}
Copied!
The above code creates a channel and notifies you through the observer block. It first instantiates the AmityChannelRepository, a class that contains all channel-related methods. Then it calls createChannel: to obtain the LiveObject and observe it in order to obtain the final channel model.
The AmityNotificationToken returned by the observe: is saved in self.channelToken, a strongly referenced property. This is needed in order to prevent the observe block from being released. You should note that this block can get called multiple times when the underlying data for the channel updates. If you don't want to get notified, you can call channelToken.invalidate(). As soon as the token gets invalidated, observer is automatically removed from that channel.
In the case that there is already an existing channel with the same channelID, the LiveObject will notify you with an error .
The channelId parameter in createChannel: can be nil: when this happens, the SDK will generate a unique channelId for this channel, ensuring no unique ID conflicts.

Create Conversation

The Chat SDK provides a convenient createConversation: method which creates a conversation channel type. You can use either createChannel or createConversation method directly as well.
1
var channelToken: AmityNotificationToken?
2
3
...
4
5
let builder = AmityConversationChannelBuilder()
6
7
builder.setUserIds(userIds) // Required
8
builder.setDisplayName("my-conversation-channel_\(randomId)") // optional
9
builder.setTags(["ch-conv","ios-sdk"]) // optional
10
builder.setMetadata(["sdk_type":"ios"]) // optional
11
12
channelObject = channelRepository.createChannel().conversation(with: builder)
13
channelToken = channelObject.observe { channelObject, error in
14
// Do Something
15
}
Copied!
Conversation channel is unique based on its membership. When creating conversation, the system will check if a channel with the same membership already exists. If such channel already exists, the system will return existing channel instead of creating a new one.

Join Channel

1
let channelObject: AmityObject<AmityChannel> = repository.joinChannel("channel-id")
2
3
channelNotification = channelObject.observe { channelObject, error in
4
...
5
}
Copied!
joinChannel: is an idempotent method, this means it can be called multiple times throughout the lifecycle of the application, and you can expect this method to always return the same channel. Because of this, you can also use joinChannel: any time you need to fetch a channel, even if you know the user may already be in the channel.

Get Channel

In the case where you'd like to fetch a channel's data without joining, the getChannel: method can be used:
1
let liveChannel = repository.getChannel("channel3")
2
3
channelNotification = liveChannel.observe { liveChannel, error in
4
...
5
}
Copied!

Channel Membership

You can observe the live channel to determine changes in the membership status. If user is banned from the channel, you would want to show appropriate UI and move from the chat screen.
1
var token: AmityNotificationToken?
2
3
...
4
5
token = channelRepo.getChannel("your-channel-id").observe { liveObject, error in
6
guard let channel = liveObject.object else { return }
7
8
switch channel.currentUserMembership {
9
case .banned:
10
// Show appropriate ui when user is banned from channel
11
break
12
case .member:
13
// ...
14
break
15
default:
16
break
17
}
18
}
19
Copied!

Channel Query

AmityChannelRepository provides a way to query list of channels using getChannels() method. It returns a AmityCollection of all the matching channels available. This live collection returned will automatically update and notify you of any channel modifications as well.
SDK provides seven builder classes:
    AmityStandardChannelQueryBuilder
    AmityPrivateChannelQueryBuilder
    AmityByTypesChannelQueryBuilder
    AmityBroadcastChannelQueryBuilder
    AmityConversationChannelQueryBuilder
    AmityCommunityChannelQueryBuilder
    AmityLiveChannelQueryBuilder
These builder classes should be used to construct a query and then used alongside getChannels method to fetch list of channels.
1
switch channelType {
2
case .byTypes:
3
let builderSet: Set<String> = Set(arrayLiteral: "standard", "private")
4
let builder = AmityByTypesChannelQueryBuilder(types: builderSet, channelQueryFilter: channelFilter, includingTags: includingTags, excludingTags: excludingTags)
5
channelsCollection = repository.getChannels().byTypes(with: builder).query()
6
case .broadcast:
7
let builder = AmityBroadcastChannelQueryBuilder(channelQueryFilter: channelFilter, includingTags: includingTags, excludingTags: excludingTags)
8
channelsCollection = repository.getChannels().broadcast(with: builder).query()
9
case .conversation:
10
let builder = AmityConversationChannelQueryBuilder(includingTags: nil, excludingTags: nil)
11
channelsCollection = repository.getChannels().conversation(with: builder).query()
12
case .live:
13
let builder = AmityLiveChannelQueryBuilder(includingTags: includingTags, excludingTags: excludingTags, includeDeleted: false)
14
channelsCollection = repository.getChannels().liveType(with: builder).query()
15
case .community:
16
let builder = AmityCommunityChannelQueryBuilder(filter: .userIsMember, includingTags: includingTags, excludingTags: excludingTags, includeDeleted: false)
17
channelsCollection = repository.getChannels().communityType(with: builder).query()
18
}
19
20
channelsToken = channelsCollection?.observe { [weak self] _, _, _ in
21
// Update datasource
22
}
Copied!
If you use a UITableView or UICollectionView to display channel list data, the ideal location to reload table data is directly in the observe block of the LiveObject that you are displaying, as shown in the example above.

Channel Filtering

You can filter channels by various criteria such as includingTags, excludingTags, includeDeleted channels, etc. All these filters are available in QueryBuilder classes for channel.

Metadata

Metadata is a general purpose data store that is automatically synchronized to all the channel members. It is meant as an elegant mechanism to store contextual information about a specific channel. The data can be any number of JSON key-value pairs up to 100 kb. Example use cases include:
    Conversation title or cover photo
    Global conversation settings
Metadata is implemented with last writer wins semantics: multiple mutations by independent users to the metadata object will result in a single stored value. No locking, merging, or other coordination is performed across multiple writes on the data.
To set metadata, call the setMetadata: method:
1
let channelUpdater = AmityChannelUpdateBuilder(id: "channel-id", andClient: client)
2
3
channelUpdater.setMetadata(["hello": "world"])
4
5
channelUpdater.update()
Copied!
The completion block will be triggered with the outcome of the request. The latest metadata of the channel is always exposed as part of the metadata property on the channel model.

Display Name

Every channel contains an optional displayName property. This property is mainly used to identify the channel in push notifications, but it is also exposed to the application via AmityChannel object.
You can set a channel's displayName with the following method:
1
let channelUpdater = AmityChannelUpdateBuilder(id: "channel-id", andClient: client)
2
3
channelUpdater.setDisplayName("Channel Amity")
4
5
channelUpdater.update().observe({ (channel, error) in
6
...
7
})
8
Copied!
An optional completion callback is available to inform you on whether the request has succeeded or not.

Participation

All participation related methods in a channel fall under a separate AmityChannelParticipation class. Before calling any participation methods, you must ensure to first instantiate a repository instance using the AmityClient instance you created on setup and a valid channelId:
1
let membershipParticipation = AmityChannelParticipation(client: client, andChannel: "channel1")
Copied!

Members Query

The participation membership provides a list of all members in the given channel as a LiveObject.
1
memberNotification = membershipParticipation.getMembers(filter: .all, sortBy: .firstCreated, roles: roles).observe { (collection, change, error) in
2
self?.tableView.reloadData()
3
}
Copied!

Manage Members

The participation membership also provides classes to add and remove members, as well as removing yourself as a member of the channel (leaving the channel).
1
// add 'user1' and 'user2' to this channel
2
membershipParticipation.addMembers(["user1", "user2"], completion: nil)
3
4
// remove 'user3' from this channel
5
membershipParticipation.removeMembers(["user3"], completion: nil)
6
7
// leave this channel
8
var channelRepository = AmityChannelRepository(client: client)
9
channelRepository.leaveChannel("channel-id", withCompletion: nil)
Copied!

Reading Status And Unread Count

The AmityChannelRepository object exposes a totalUnreadCount property that reflects the number of messages that the current user has yet to read. This count is the sum of all the unreadCount channels properties where the user is already a member.
1
// repository is a `AmityChannelRepository` instance
2
let userTotalUnreadCount = repository.totalUnreadCount
3
4
let channelObject: AmityObject<AmityChannel> = repository.getChannel("channel1")
5
let channelUnreadCount = channel.object?.unreadCount
Copied!
To let the server know when the current user is reading one channel, hence resetting that channel unreadCount to zero, the participation membership exposes the startReading and stopReading methods.
You can call both methods as much you'd like, the SDK takes care of multi-device management: therefore a user can read multiple channels, from one or multiple devices at the same time. In case of an abrupt disconnection (whether because the app was killed, or the internet went down, etc.), the SDK backend will automatically call the stopReading on the user's behalf.
1
// start reading a channel
2
membershipParticipation.startReading()
3
4
// stop reading a channel
5
membershipParticipation.stopReading()
Copied!

Moderation

AmityChannelModeration class provides various methods to moderate the users present in any given channel. You can ban/unban/mute users, assign or remove roles from users.

Permission

You can check your permission in channel using hasPermission(permission:forChannel:_:) method from AmityClient.
Last modified 25d ago