Channel groups
Channel groups let you subscribe to multiple channels with a single subscription. Add channels to a group and receive messages from all of them at once.
Use channel groups to:
- Subscribe to all user channels with one call
- Monitor presence across multiple channels
- Manage subscriptions dynamically without reconnecting
Publishing to a channel group is not supported. Publish to each channel individually.
Requires Stream Controller
Enable Stream Controller for your key in the Admin Portal. See Enable the features your app calls.
Get channel group reference
Get a reference to a channel group with getChannelGroup(). This returns a handle to manage the group without creating it on the server.
If the group exists, the reference points to it. Otherwise, the handle creates the group when you add channels.
Method signature
This method takes the following parameters:
1chat.getChannelGroup(id: String) -> ChannelGroupImpl
Input
idrequired#- Unique identifier for the channel group.
Output
| Type | Description |
|---|---|
ChannelGroupImpl | A ChannelGroup object you can use to manage the group. |
Sample code
Sample code
The code samples in Swift Chat SDK focus on asynchronous code execution.
You can also write synchronous code as the parameters are shared between the async and sync methods but we don't provide usage examples of such.
Get a reference to a channel group named my-channel-group.
1// Assumes a "ChatImpl" reference named "chat"
2let channelGroup = chat.getChannelGroup(id: "my-channel-group")
Remove channel group
Delete a channel group from the server with removeChannelGroup().
Method signature
This method takes the following parameters:
1chat.removeChannelGroup(id: String) async throws
Input
idrequired#- Unique identifier of the channel group to remove.
Output
This method doesn't return any value.
Sample code
Remove a channel group named my-channel-group.
1// Assumes a "ChatImpl" reference named "chat"
2Task {
3 try await chat.removeChannelGroup(id: "my-channel-group")
4 debugPrint("Channel group removed successfully")
5}
List channels
Get a paginated list of all channels in a channel group with listChannels().
Method signature
This method takes the following parameters:
1channelGroup.listChannels(
2 filter: String? = nil,
3 sort: [PubNub.ObjectSortField] = [],
4 limit: Int? = nil,
5 page: PubNubHashedPage? = nil
6) async throws -> (channels: [ChannelImpl], page: PubNubHashedPage?)
Input
filter#- Expression used to filter the results. Returns only the channels whose properties satisfy the given expression. The filter language is defined here.
sort#- An array to specify the sort order. Available options are
id,name, andupdated. Useascendingordescendingto specify the sorting direction. limit#- Number of objects to return in response. The maximum value is
100. page#- Object used for pagination to define which previous or next result page you want to fetch.
Output
| Type | Description |
|---|---|
(channels: [ChannelImpl], page: PubNubHashedPage?) | A tuple containing a set of channels with pagination information. |
Sample code
List all channels in a channel group.
1// Assumes a "ChatImpl" reference named "chat"
2Task {
3 let channelGroup = chat.getChannelGroup(id: "my-channel-group")
4 let result = try await channelGroup.listChannels()
5
6 for channel in result.channels {
7 debugPrint("Channel: \(channel.id)")
8 }
9}
Add channels
Add Channel entities to a channel group with add(channels:).
Method signature
This method takes the following parameters:
1channelGroup.add(channels: [ChannelImpl]) async throws
Input
Output
This method doesn't return any value.
Sample code
Add two channels to a channel group.
1// Assumes a "ChatImpl" reference named "chat"
2Task {
3 let channelGroup = chat.getChannelGroup(id: "my-channel-group")
4 let supportChannel = try await chat.getChannel(channelId: "support-channel")
5 let generalChannel = try await chat.getChannel(channelId: "general-channel")
6
7 if let supportChannel, let generalChannel {
8 try await channelGroup.add(channels: [supportChannel, generalChannel])
9 debugPrint("Channels added successfully")
10 }
11}
Add channel identifiers
Add channels to a group by ID with addChannelIdentifiers(_:). This avoids fetching full Channel entities.
No validation
This method does not validate that the channel IDs exist.
Method signature
This method takes the following parameters:
1channelGroup.addChannelIdentifiers(_ ids: [String]) async throws
Input
idsrequired#- Array of channel IDs to add to the group.
Output
This method doesn't return any value.
Sample code
Add channels by their IDs.
1// Assumes a "ChatImpl" reference named "chat"
2Task {
3 let channelGroup = chat.getChannelGroup(id: "my-channel-group")
4 try await channelGroup.addChannelIdentifiers(["support-channel", "general-channel"])
5 debugPrint("Channel identifiers added successfully")
6}
Remove channels
Remove Channel entities from a channel group with remove(channels:).
Method signature
This method takes the following parameters:
1channelGroup.remove(channels: [ChannelImpl]) async throws
Input
Output
This method doesn't return any value.
Sample code
Remove channels from a channel group.
1// Assumes a "ChatImpl" reference named "chat"
2// Assumes "ChannelImpl" references named "supportChannel" and "generalChannel"
3Task {
4 let channelGroup = chat.getChannelGroup(id: "my-channel-group")
5 try await channelGroup.remove(channels: [supportChannel, generalChannel])
6 debugPrint("Channels removed successfully")
7}
Remove channel identifiers
Remove channels from a group by ID with removeChannelIdentifiers(_:).
No validation
This method does not validate that the channel IDs exist in the group.
Method signature
This method takes the following parameters:
1channelGroup.removeChannelIdentifiers(_ ids: [String]) async throws
Input
idsrequired#- Array of channel IDs to remove from the group.
Output
This method doesn't return any value.
Sample code
Remove channels by their IDs.
1// Assumes a "ChatImpl" reference named "chat"
2Task {
3 let channelGroup = chat.getChannelGroup(id: "my-channel-group")
4 try await channelGroup.removeChannelIdentifiers(["support-channel", "general-channel"])
5 debugPrint("Channel identifiers removed successfully")
6}
Watch channel group
Subscribe to all channels in the group and receive messages with onMessageReceived(). The callback fires whenever a message arrives on any channel in the group.
You can also use channelGroup.stream.messages() for an AsyncStream-based approach.
Deprecation
connect() is deprecated. Use onMessageReceived() (closure-based) or channelGroup.stream.messages() (AsyncStream-based) instead.
Method signature
1channelGroup.onMessageReceived(
2 callback: @escaping (MessageImpl) -> Void
3) -> AutoCloseable
Input
callbackrequired#- Closure called whenever a new message is published on any channel in the group.
Output
| Type | Description |
|---|---|
AutoCloseable | An object you must retain. When released or closed, the listener stops. |
Sample code
Start receiving messages from all channels in a group.
- AsyncStream
- Closure
1// Assumes a "ChatImpl" reference named "chat"
2Task {
3 let channelGroup = chat.getChannelGroup(id: "my-channel-group")
4
5 for await message in channelGroup.connect() {
6 debugPrint("Received message on channel \(message.channelId): \(message.text)")
7 }
8}
1// Assumes a "ChannelGroupImpl" reference named "channelGroup"
2
3// Important: Keep a strong reference to the returned "AutoCloseable" object as long as you want
4// to receive updates. If the "AutoCloseable" is deallocated, the stream will be cancelled,
5// and no further items will be produced. You can also stop receiving messages manually
6// by calling the "close()" method on the "AutoCloseable" object.
7autoCloseable = channelGroup.connect { message in
8 debugPrint("Received message on channel \(message.channelId): \(message.text)")
9}
Get present users
Get a list of users currently present on any channel in the group with whoIsPresent().
Requires Presence
Enable Presence for your keyset in the Admin Portal.
Method signature
This method has the following signature:
1channelGroup.whoIsPresent(
2 limit: Int = 1000,
3 offset: Int? = 0
4) async throws -> [String: [String]]
Input
Output
| Type | Description |
|---|---|
[String: [String]] | A dictionary where each key is a channel ID and the value is an array of user IDs present on that channel. |
Sample code
Get all users present on channels in a group.
1// Assumes a "ChatImpl" reference named "chat"
2Task {
3 let channelGroup = chat.getChannelGroup(id: "my-channel-group")
4 let presenceByChannel = try await channelGroup.whoIsPresent()
5
6 for (channelId, userIds) in presenceByChannel {
7 debugPrint("Channel \(channelId) has users: \(userIds)")
8 }
9}
Stream presence
Receive real-time updates when users join or leave any channel in the group with onPresenceChanged().
You can also use channelGroup.stream.presenceChanges() for an AsyncStream-based approach.
Requires Presence
Enable Presence for your keyset in the Admin Portal.
Deprecation
streamPresence() is deprecated. Use onPresenceChanged() (closure-based) or channelGroup.stream.presenceChanges() (AsyncStream-based) instead.
Method signature
1channelGroup.onPresenceChanged(
2 callback: @escaping ([String: [String]]) -> Void
3) -> AutoCloseable
Input
callbackrequired#- Closure called with a dictionary of channel IDs to present user ID arrays whenever presence changes.
Output
| Type | Description |
|---|---|
AutoCloseable | An object you must retain. When released or closed, the listener stops. |
Sample code
Stream presence updates for all channels in a group.
- AsyncStream
- Closure
1// Assumes a "ChatImpl" reference named "chat"
2Task {
3 let channelGroup = chat.getChannelGroup(id: "my-channel-group")
4
5 for await presenceByChannel in channelGroup.streamPresence() {
6 for (channelId, userIds) in presenceByChannel {
7 debugPrint("Channel \(channelId) now has users: \(userIds)")
8 }
9 }
10}
1// Assumes a "ChannelGroupImpl" reference named "channelGroup"
2
3// Important: Keep a strong reference to the returned "AutoCloseable" object as long as you want
4// to receive updates. If the "AutoCloseable" is deallocated, the stream will be cancelled,
5// and no further items will be produced. You can also stop receiving presence updates manually
6// by calling the "close()" method on the "AutoCloseable" object.
7autoCloseable = channelGroup.streamPresence { presenceByChannel in
8 for (channelId, userIds) in presenceByChannel {
9 debugPrint("Channel \(channelId) now has users: \(userIds)")
10 }
11}