Manage the user-channel membership relationship
Requires App Context
To set up and manage channel membership, you must enable App Context for your app's keyset in the Admin Portal.
When a user joins a channel or gets invited to it, a membership relationship between that user and the channel is created (Membership
entity). The membership ends when this user leaves the channel.
Read on to learn how to check and update user-channel membership.
Get members
getMembers()
returns the list of all channel members.
Method signature
This method takes the following parameters:
channel.getMembers(
limit: Int? = nil,
page: PubNubHashedPage? = nil,
filter: String? = nil,
sort: [PubNub.MembershipSortField] = []
) async throws -> (memberships: [MembershipImpl], page: PubNubHashedPage?)
Input
Parameter | Description |
---|---|
limit Type: Int Default: 100 | Number of objects to return in response. The default (and maximum) value is 100 (set through the underlying Swift SDK). |
page Type: PubNubHashedPage? Default: nil | Object used for pagination to define which previous or next result page you want to fetch. |
filter Type: String Default: nil | Expression used to filter the results. Returns only these members whose properties satisfy the given expression. The filter language is defined here. |
sort Type: [PubNub.MembershipSortField] Default: [] | A collection to specify the sort order. Available options are id , name , and updated . Use asc or desc to specify the sorting direction, or specify null to take the default sorting direction (ascending). For example: {name: "asc"} . Unless specified otherwise, the items are sorted by the last updated date. Defaults to an empty list. |
Output
Parameter | Description |
---|---|
(memberships: [MembershipImpl], page: PubNubHashedPage?) | A tuple containing a set of channel members with membership and pagination information indicating the start, end, and total count of the members. |
Basic usage
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.
List all members of the support
channel on the premium
support plan.
// Assuming you have a reference of type "ChatImpl" named "chat"
Task {
// Fetch the metadata of the "support" channel
if let channel = try await chat.getChannel(channelId: "support") {
// Check if the channel's custom data includes the "premium" support plan
if let customData = channel.custom, customData["supportPlan"]?.stringOptional == "premium" {
// List all members of the "support" channel
let members = try await channel.getMembers()
debugPrint("Fetched members: \(members)")
debugPrint("Next page (if any): \(String(describing: members.page))")
} else {
debugPrint("Channel not found")
}
} else {
debugPrint("Channel not found")
show all 17 linesGet membership
getMemberships()
returns the list of all channel memberships of a given user.
To get a list of all existing channels, use the getChannels()
method.
Method signature
This method takes the following parameters:
user.getMemberships(
limit: Int? = nil,
page: PubNubHashedPage? = nil,
filter: String? = nil,
sort: [PubNub.MembershipSortField] = []
) async throws -> (memberships: [MembershipImpl], page: PubNubHashedPage?)
Input
Parameter | Description |
---|---|
limit Type: Int Default: 100 | Number of objects to return in response. The default (and maximum) value is 100 (set through the underlying Swift SDK). |
page Type: PubNubHashedPage Default: n/a | Object used for pagination to define which previous or next result page you want to fetch. |
filter Type: String Default: n/a | Expression used to filter the results. Returns only these members whose properties satisfy the given expression. The filter language is defined here. |
sort Type: [PubNub.MembershipSortField] Default: [] | A collection to specify the sort order. Available options are id , name , and updated . Use asc or desc to specify the sorting direction, or specify null to take the default sorting direction (ascending). For example: {name: "asc"} . Unless specified otherwise, the items are sorted by the last updated date. Defaults to an empty list. |
Output
Parameter | Description |
---|---|
(memberships: [MembershipImpl], page: PubNubHashedPage?) | Object containing a set of memberships and pagination information indicating the start, end, and total count of the memberships. |
Basic usage
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.
Find out which channels the support_agent_15
user is a member of.
// Assuming you have a reference of type "ChatImpl" named "chat"
Task {
if let user = try await chat.getUser(userId: "support_agent_15") {
let memberships = try await user.getMemberships()
let channelIds = memberships.memberships.map { $0.channel.id }
debugPrint("User 'support_agent_15' is a member of channels: \(channelIds)")
debugPrint("Next page (if any): \(String(describing: memberships.page))")
} else {
debugPrint("User not found")
}
}
Get updates
You can receive updates when specific user-channel Membership
object(s) are added, edited, or removed using the following methods:
streamUpdates()
checks updates on a singleMembership
object and it's tied to an instance of theMembership
class.streamUpdatesOn()
checks updates on a list ofMembership
objects and it's tied to theMembership
class.
Both methods return an asynchronous stream which produces a new value whenever someone adds, changes, or removes membership data.
Underneath, these methods subscribe the current user to a channel and add an objects event listener to receive all objects
events of type membership
. These methods also return the unsubscribe
function you can invoke to stop receiving objects
events and unsubscribe from the channel.
Method Signature
These methods provide asynchronous streams for real-time updates on membership changes:
-
streamUpdates()
membership.streamUpdates() -> AsyncStream<MembershipImpl>
-
streamUpdatesOn()
(static)MembershipImpl.streamUpdatesOn(
memberships: [MembershipImpl]
) -> AsyncStream<MembershipImpl>
Input
Parameter | Required in streamUpdates() | Required in streamUpdatesOn() | Description |
---|---|---|---|
memberships Type: [MembershipImpl] Default: n/a | No | Yes | A collection of MembershipImpl objects from which you want to receive updates. |
Output
Component | Description |
---|---|
AsyncStream<MembershipImpl> | An asynchronous stream providing updates on membership changes. It allows for real-time processing as new data becomes available. |
Basic usage
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 updates on the first user membership.
streamUpdates()
- AsyncStream
- Closure
// Assuming you have a reference of type "ChatImpl" named "chat"
Task {
if let membership = try await chat.currentUser.getMemberships(limit: 1).memberships.first {
for await updatedMembership in membership.streamUpdates() {
if let updatedMembership {
debugPrint("Received update for membership: \(updatedMembership)")
}
}
} else {
debugPrint("Membership not found")
}
}
// Important: Keep a strong reference to the returned "AutoCloseable" object as long as you want
// to receive new updates. If the "AutoCloseable" is deallocated, the stream will be cancelled,
// and no further items will be produced. You can also stop receiving updates manually
// by calling the "close()" method on the "AutoCloseable" object.
/// Assuming you have a "membership" instance of "MembershipImpl" type
autoCloseable = membership.streamUpdates { updatedMembership in
if let updatedMembership = updatedMembership {
debugPrint("Received update for membership with ID: \(updatedMembership.user.id)")
} else {
debugPrint("Membership has been deleted")
}
}
Get updates on the first page of user memberships.
streamUpdatesOn()
- AsyncStream
- Closure
Task {
let getMembershipsRes = try await chat.currentUser.getMemberships(limit: 10)
let memberships = getMembershipsRes.memberships
for await updatedMembership in MembershipImpl.streamUpdatesOn(memberships: memberships) {
debugPrint("Received update for membership: \(updatedMembership)")
}
}
// Important: Keep a strong reference to the returned "AutoCloseable" object as long as you want
// to receive new updates. If the "AutoCloseable" is deallocated, the stream will be cancelled,
// and no further items will be produced. You can also stop receiving updates manually
// by calling the "close()" method on the "AutoCloseable" object
// Assuming you have an array of "MembershipImpl" objects named "memberships"
autoCloseable = MembershipImpl.streamUpdatesOn(memberships: memberships) { updatedMemberships in
for updatedMembership in updatedMemberships {
debugPrint("Received update for membership with channel ID: \(updatedMembership.channel.id)")
}
}
Update
update()
updates the channel membership information for a given user.
Method signature
This method takes the following parameters:
membership.update(
custom: [String: JSONCodableScalar]
) async throws -> MembershipImpl
Input
Parameter | Description |
---|---|
custom *Type: [String: JSONCodableScalar] Default: n/a | Any custom properties or metadata associated with the channel-user membership in the form of a JSON. Values must be scalar only; arrays or objects are not supported. App Context filtering language doesn’t support filtering by custom properties. |
Output
Parameter | Description |
---|---|
MembershipImpl | Returned (modified) object containing the membership data. |
Basic usage
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.
Assign the premium-support
role to support_agent_15
on the high-priority-incidents
channel.
// Assuming you have a reference of type "ChatImpl" named "chat"
Task {
if let user = try await chat.getUser(userId: "support_agent_15") {
if let membership = try await user.getMemberships(filter: "channel.id == 'high-priority-incidents'").memberships.first {
let updatedMembership = try await membership.update(custom: ["role": "premium-support"])
debugPrint("Updated membership: \(updatedMembership)")
} else {
debugPrint("No memberhips found")
}
} else {
debugPrint("User not found")
}
}