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] = [],
completion: ((Swift.Result<(memberships: [MembershipImpl], page: PubNubHashedPage?), Error>) -> Void)? = nil
)

Input

ParameterTypeRequiredDefaultDescription
limitIntNo100Number of objects to return in response. The default (and maximum) value is 100 (set through the underlying Swift SDK).
pagePubNubHashedPageNon/aObject used for pagination to define which previous or next result page you want to fetch.
filterStringNon/aExpression used to filter the results. Returns only these members whose properties satisfy the given expression. The filter language is defined here.
sort[PubNub.MembershipSortField]No[]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

TypeDescription
(memberships: [MembershipImpl], page: PubNubHashedPage?)Object containing a set of channel members with membership and pagination information indicating the start, end, and total count of the members.

Basic usage

List all members of the support channel on the premium support plan.

/// Assuming you have a "chat" instance available
/// Fetch the metadata of the "support" channel
chat?.getChannel(
channelId: "support"
) {
switch $0 {
case let .success(channel):
if let channel = channel {
debugPrint("Fetched channel metadata with ID: \(channel.id)")

/// 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
channel.getMembers(
completion: { result in
show all 33 lines

Get 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] = [],
completion: ((Swift.Result<(memberships: [ChatType.ChatMembershipType], page: PubNubHashedPage?), Error>) -> Void)? = nil
)

Input

ParameterTypeRequiredDefaultDescription
limitIntNo100Number of objects to return in response. The default (and maximum) value is 100 (set through the underlying Swift SDK).
pagePubNubHashedPageNon/aObject used for pagination to define which previous or next result page you want to fetch.
filterStringNon/aExpression used to filter the results. Returns only these members whose properties satisfy the given expression. The filter language is defined here.
sort[PubNub.MembershipSortField]No[]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

TypeDescription
(memberships: [ChatType.ChatMembershipType], page: PubNubHashedPage?)Object containing a set of memberships and pagination information indicating the start, end, and total count of the memberships.

Basic usage

Find out which channels the support_agent_15 user is a member of.

/// Assuming you have a "chat" instance available
/// Fetch the metadata of the user "support_agent_15"
chat?.getUser(
userId: "support_agent_15"
) {
switch $0 {
case let .success(user):
if let user = user {
debugPrint("Fetched user metadata with ID: \(user.id)")

/// List all channels that "support_agent_15" is a member of
user.getMemberships { result in
switch result {
case let .success((memberships, _)):
let channelIds = memberships.map { $0.channel.id }
show all 27 lines

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 single Membership object and it's tied to an instance of the Membership class.
  • streamUpdatesOn() checks updates on a list of Membership objects and it's tied to the Membership class.

Both methods accept a callback function as an argument. The Chat SDK invokes this callback 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 take the following parameters:

  • streamUpdates()

    membership.streamUpdates(
    callback: @escaping ((MembershipImpl)?) -> Void
    ) -> AutoCloseable
  • streamUpdatesOn() (static)

    Membership.streamUpdatesOn(
    memberships: [MembershipImpl],
    callback: @escaping (([MembershipImpl]) -> Void)
    ) -> AutoCloseable

Input

ParameterTypeRequired in streamUpdates()Required in streamUpdatesOn()DefaultDescription
memberships[MembershipImpl]NoYesn/aA collection of MembershipImpl objects for which you want to get updates.
callback@escaping ((MembershipImpl)?) -> VoidYesNon/aFunction that takes a single MembershipImpl object. It defines the custom behavior to be executed when detecting membership changes.
callback@escaping (([MembershipImpl]) -> Void)NoYesn/aFunction that takes a set of MembershipImpl objects. It defines the custom behavior to be executed when detecting membership changes.

Output

TypeDescription
AutoCloseableInterface that lets you stop receiving membership-related updates (objects events) by invoking the close() method.

Basic usage

Get updates on the first user membership.

  • streamUpdates()

    /// Assuming you have a "chat" instance available
    /// Fetch memberships of the current user
    chat.currentUser.getMemberships(limit: 1) { result in
    switch result {
    case let .success((memberships, _)):
    if let firstMembership = memberships.first {
    debugPrint("Fetched first membership with ID: \(firstMembership.user.id)")

    /// Stream updates on the first membership
    let autoCloseable = firstMembership.streamUpdates { updatedMembership in
    if let updatedMembership = updatedMembership {
    debugPrint("Received update for membership with ID: \(updatedMembership.user.id)")
    } else {
    debugPrint("No updates received")
    }
    show all 25 lines

Get updates on the first page of user memberships.

  • streamUpdatesOn()

    /// Assuming you have a "chat" instance available
    /// Fetch memberships of the current user
    chat.currentUser?.getMemberships(limit: 10) { result in
    switch result {
    case let .success((memberships, page)):
    if memberships.isEmpty {
    debugPrint("No memberships found")
    } else {
    debugPrint("Fetched \(memberships.count) memberships")

    /// Stream updates on the first page of memberships
    let autoCloseable = Membership.streamUpdatesOn(memberships: memberships) { updatedMemberships in
    for updatedMembership in updatedMemberships {
    debugPrint("Received update for membership with ID: \(updatedMembership.id)")
    }
    show all 23 lines

Other examples

Stop listening to updates on the first user membership.

  • streamUpdates()

    var autoCloseable: AutoCloseable?

    /// Assuming you have a "chat" instance available
    /// Fetch memberships of the current user
    chat.currentUser.getMemberships(limit: 1) { result in
    switch result {
    case let .success((memberships, _)):
    if let firstMembership = memberships.first {
    debugPrint("Fetched first membership with ID: \(firstMembership.user.id)")

    /// Stream updates on the first membership
    autoCloseable = firstMembership.streamUpdates { updatedMembership in
    if let updatedMembership = updatedMembership {
    debugPrint("Received update for membership with ID: \(updatedMembership.user.id)")
    } else {
    show all 33 lines

    Stop listening to updates on the first page of user memberships.

    • streamUpdatesOn()
    var autoCloseable: AutoCloseable?

    /// Assuming you have a "chat" instance available
    /// Fetch memberships of the current user
    chat.currentUser.getMemberships(limit: 10) { result in
    switch result {
    case let .success((memberships, _)):
    if memberships.isEmpty {
    debugPrint("No memberships found")
    } else {
    debugPrint("Fetched \(memberships.count) memberships")

    /// Stream updates on the first page of memberships
    autoCloseable = MembershipImpl.streamUpdatesOn(memberships: memberships) { updatedMemberships in
    for updatedMembership in updatedMemberships {
    show all 31 lines

Update

update() updates the channel membership information for a given user.

Method signature

This method takes the following parameters:

membership.update(
custom: [String: JSONCodableScalar],
completion: ((Swift.Result<MembershipImpl, Error>) -> Void)? = nil
)

Input

ParameterTypeRequiredDefaultDescription
custom[String: JSONCodableScalar]Yesn/aAny 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

TypeDescription
MembershipImplReturned (modified) object containing the membership data.

Basic usage

Assign the premium-support role to support_agent_15 on the high-priority-incidents channel.

/// Assuming you have a "chat" instance available
/// Reference the "support_agent_15" user
chat.getUser(userId: "support_agent_15") { userResult in
switch userResult {
case let .success(user):
if let user = user {
debugPrint("Fetched user with ID: \(user.id)")

/// Get the list of all user memberships and filter out the right channel
user.getMemberships(filter: "channel.id == 'high-priority-incidents'") { membershipsResult in
switch membershipsResult {
case let .success((memberships, _)):
if let membership = memberships.first {
debugPrint("Fetched membership for channel with ID: \(membership.channel.id)")
/// Add custom metadata to the user membership
show all 37 lines
Last updated on