---
source_url: https://www.pubnub.com/docs/chat/swift-chat-sdk/build/features/channels/membership
title: Manage the user-channel membership relationship
description: Learn to manage user-channel memberships with the PubNub Swift Chat SDK for dynamic chat application member management.
updated_at: 2026-09-30T07:20:08.000Z
---

# Manage the user-channel membership relationship

> For AI agents: documentation index at https://www.pubnub.com/llms-full.txt

:::note Requires App Context
Enable [App Context](https://youtu.be/9UEoSlngpYI) for your keyset in the [Admin Portal](https://admin.pubnub.com/).
:::

A [`Membership` entity](https://www.pubnub.com/docs/chat/swift-chat-sdk/learn/chat-entities/membership.md) is created when a user [joins](https://www.pubnub.com/docs/chat/swift-chat-sdk/build/features/channels/join.md) or is [invited](https://www.pubnub.com/docs/chat/swift-chat-sdk/build/features/channels/invite.md) to a channel, and ends when the user [leaves](https://www.pubnub.com/docs/chat/swift-chat-sdk/build/features/channels/leave.md).

## Get members

Get all members of a channel with `getMembers()`.

### Method signature

This method takes the following parameters:

```swift
channel.getMembers(
    limit: Int? = nil,
    page: PubNubHashedPage? = nil,
    filter: String? = nil,
    sort: [PubNub.MembershipSortField] = []
) async throws -> (memberships: [MembershipImpl], page: PubNubHashedPage?)
```

#### Input

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| limit | Int | Optional | `100` | Number of objects to return in response. The default (and maximum) value is `100` (set through the underlying Swift SDK). |
| page | PubNubHashedPage? | Optional | `nil` | Object used for pagination to define which previous or next result page you want to fetch. |
| filter | String | Optional | `nil` | Expression used to filter the results. Returns only these members whose properties satisfy the given expression. The filter language is [defined here](https://www.pubnub.com/docs/data-storage/metadata/filtering.md). |
| sort | [PubNub.MembershipSortField] | Optional | `[]` | 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. |

### Sample code

:::tip 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.

```swift
// Assumes a "ChatImpl" reference 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")
  }
}
```

## Get membership

Get all channel [memberships](https://www.pubnub.com/docs/chat/swift-chat-sdk/learn/chat-entities/membership.md) for a user with `getMemberships()`.

To list all channels, use [`getChannels()`](https://www.pubnub.com/docs/chat/swift-chat-sdk/build/features/channels/list.md) instead.

### Method signature

This method takes the following parameters:

```swift
user.getMemberships(
    limit: Int? = nil,
    page: PubNubHashedPage? = nil,
    filter: String? = nil,
    sort: [PubNub.MembershipSortField] = []
) async throws -> (memberships: [MembershipImpl], page: PubNubHashedPage?)
```

#### Input

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| limit | Int | Optional | `100` | Number of objects to return in response. The default (and maximum) value is `100` (set through the underlying Swift SDK). |
| page | PubNubHashedPage | Optional | n/a | Object used for pagination to define which previous or next result page you want to fetch. |
| filter | String | Optional | n/a | Expression used to filter the results. Returns only these members whose properties satisfy the given expression. The filter language is [defined here](https://www.pubnub.com/docs/data-storage/metadata/filtering.md). |
| sort | [PubNub.MembershipSortField] | Optional | `[]` | 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. |

### Sample code

:::tip 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.

```swift
// Assumes a "ChatImpl" reference 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

Receive real-time updates when a [`Membership` object](https://www.pubnub.com/docs/chat/swift-chat-sdk/learn/chat-entities/membership.md) is edited with `onUpdated()`, or be notified when it is deleted with `onDeleted()`.

You can also use `membership.stream.updates()` and `membership.stream.deletions()` for `AsyncStream`-based equivalents.

For monitoring multiple memberships at once, `streamUpdatesOn()` remains available.

:::note Membership changes
These methods notify about field changes (metadata, status) for existing memberships, not additions or removals.
:::

:::note Deprecation
`streamUpdates()` is deprecated. Use `onUpdated()` and `onDeleted()` (closure-based) or `membership.stream.updates()` and `membership.stream.deletions()` (AsyncStream-based) instead.
:::

### Method signature

* `onUpdated()` — closure called when the membership metadata changes

   ```swift
   membership.onUpdated(
       callback: @escaping (MembershipImpl) -> Void
   ) -> AutoCloseable
   ```

* `onDeleted()` — closure called when the membership is deleted

   ```swift
   membership.onDeleted(
       callback: @escaping () -> Void
   ) -> AutoCloseable
   ```

* `streamUpdatesOn()` (static) — monitors multiple memberships

   ```swift
   MembershipImpl.streamUpdatesOn(
       memberships: [MembershipImpl]
   ) -> AsyncStream<MembershipImpl>
   ```

#### Input

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| callback (in onUpdated) | (MembershipImpl) -> Void | Yes | n/a | Closure called with the updated membership whenever its metadata changes. |
| callback (in onDeleted) | () -> Void | Yes | n/a | Closure called when the membership is deleted. |
| memberships (in streamUpdatesOn) | [MembershipImpl] | Yes | n/a | A collection of [`MembershipImpl` objects](https://www.pubnub.com/docs/chat/swift-chat-sdk/learn/chat-entities/membership.md) from which you want to receive updates. |

#### Output

| Parameter | Description |
| --- | --- |
| `AutoCloseable` | An object you must retain. When released or closed, the listener stops. |

### Sample code

:::tip 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.

#### Closure

```swift
// Assumes a "MembershipImpl" reference named "membership"
  
// 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.
autoCloseable = membership.streamUpdates { updatedMembership in
  // The closure receives the entire updated Membership object each time a change occurs.
  if let updatedMembership = updatedMembership {
    debugPrint("Received update for membership with ID: \(updatedMembership.user.id)")
  } else {
    debugPrint("Membership has been deleted")
  }
}
```

#### AsyncStream

```swift
// Assumes a "ChatImpl" reference named "chat"
Task {
  if let membership = try await chat.currentUser.getMemberships(limit: 1).memberships.first {
    for await updatedMembership in membership.streamUpdates() {
      // The stream returns the entire updated Membership object each time a change occurs.
      if let updatedMembership {
        debugPrint("Received update for membership: \(updatedMembership)")
      } else {
        debugPrint("Membership was deleted")
      }
    }
  } else {
    debugPrint("Membership not found")
  }
}
```

#### Watch multiple memberships

Get updates on multiple membership objects at once.

##### Closure

```swift
// Assumes an array of "MembershipImpl" objects named "memberships"
  
// 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.
autoCloseable = MembershipImpl.streamUpdatesOn(memberships: memberships) { updatedMemberships in
  // The closure receives the complete list of all memberships you're monitoring
  // each time any change occurs.
  for updatedMembership in updatedMemberships {
    debugPrint("Received update for membership with channel ID: \(updatedMembership.channel.id)")
  }
}
```

##### AsyncStream

```swift
// Assumes a "ChatImpl" reference named "chat"
Task {
  let getMembershipsRes = try await chat.currentUser.getMemberships(limit: 10)
  let memberships = getMembershipsRes.memberships
    
  for await updatedMemberships in MembershipImpl.streamUpdatesOn(memberships: memberships) {
    // The stream returns the complete list of all memberships you're monitoring
    // each time any change occurs.
    debugPrint("Received updates for memberships: \(updatedMemberships)")
  }
}
```

## Check if user is a member

`hasMember()` checks if a user is a member of the channel without fetching the full membership object.

### Method signature

```swift
channel.hasMember(
    userId: String
) async throws -> Bool
```

#### Input

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | String | Yes | n/a | ID of the user to check. |

#### Output

| Parameter | Description |
| --- | --- |
| `Bool` | `true` if the user is a member of the channel, `false` otherwise. |

### Sample code

:::tip 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.
:::

Check if `support_agent_15` is a member of the `support` channel.

```swift
// Assumes a "ChatImpl" reference named "chat"
Task {
  if let channel = try await chat.getChannel(channelId: "support") {
    let isMember = try await channel.hasMember(userId: "support_agent_15")
    if isMember {
      debugPrint("User 'support_agent_15' is a member of the 'support' channel")
    } else {
      debugPrint("User 'support_agent_15' is not a member of the 'support' channel")
    }
  } else {
    debugPrint("Channel not found")
  }
}
```

## Get single member

`getMember()` retrieves a single membership for a specific user on the channel.

### Method signature

```swift
channel.getMember(
    userId: String
) async throws -> MembershipImpl?
```

#### Input

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| userId | String | Yes | n/a | ID of the user whose membership you want to retrieve. |

#### Output

| Parameter | Description |
| --- | --- |
| `MembershipImpl?` | The membership object if the user is a member, `nil` otherwise. |

### Sample code

:::tip 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 the membership of `support_agent_15` on the `support` channel.

```swift
// Assumes a "ChatImpl" reference named "chat"
Task {
  if let channel = try await chat.getChannel(channelId: "support") {
    if let membership = try await channel.getMember(userId: "support_agent_15") {
      debugPrint("Found membership for user: \(membership.user.id)")
      debugPrint("Membership custom data: \(String(describing: membership.custom))")
    } else {
      debugPrint("User 'support_agent_15' is not a member of the 'support' channel")
    }
  } else {
    debugPrint("Channel not found")
  }
}
```

## Check if user belongs to channel

`isMemberOf()` checks if the user has a membership on a specific channel.

### Method signature

```swift
user.isMemberOf(
    channelId: String
) async throws -> Bool
```

#### Input

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | String | Yes | n/a | ID of the channel to check. |

#### Output

| Parameter | Description |
| --- | --- |
| `Bool` | `true` if the user is a member of the channel, `false` otherwise. |

### Sample code

:::tip 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.
:::

Check if the user `support_agent_15` belongs to the `support` channel.

```swift
// Assumes a "ChatImpl" reference named "chat"
Task {
  if let user = try await chat.getUser(userId: "support_agent_15") {
    let isMember = try await user.isMemberOf(channelId: "support")
    if isMember {
      debugPrint("User 'support_agent_15' is a member of the 'support' channel")
    } else {
      debugPrint("User 'support_agent_15' is not a member of the 'support' channel")
    }
  } else {
    debugPrint("User not found")
  }
}
```

## Get single membership

`getMembership()` retrieves a single membership for the user on a specific channel.

### Method signature

```swift
user.getMembership(
    channelId: String
) async throws -> MembershipImpl?
```

#### Input

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| channelId | String | Yes | n/a | ID of the channel whose membership you want to retrieve. |

#### Output

| Parameter | Description |
| --- | --- |
| `MembershipImpl?` | The membership object if the user is a member, `nil` otherwise. |

### Sample code

:::tip 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 the membership of user `support_agent_15` on the `support` channel.

```swift
// Assumes a "ChatImpl" reference named "chat"
Task {
  if let user = try await chat.getUser(userId: "support_agent_15") {
    if let membership = try await user.getMembership(channelId: "support") {
      debugPrint("Found membership in channel: \(membership.channel.id)")
      debugPrint("Membership custom data: \(String(describing: membership.custom))")
    } else {
      debugPrint("User 'support_agent_15' is not a member of the 'support' channel")
    }
  } else {
    debugPrint("User not found")
  }
}
```

## Update

Update a user’s channel [membership](https://www.pubnub.com/docs/chat/swift-chat-sdk/learn/chat-entities/membership.md) information with `update()`.

### Method signature

This method takes the following parameters:

```swift
membership.update(
    custom: [String: JSONCodableScalar],
    status: String? = nil,
    type: String? = nil
) async throws -> MembershipImpl
```

#### Input

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| custom | [String: JSONCodableScalar] | Yes | 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](https://www.pubnub.com/docs/data-storage/metadata/filtering.md) doesn’t support filtering by custom properties. |
| status | String | Optional | `nil` | Optional status value for the membership. |
| type | String | Optional | `nil` | Optional type value for the membership. |

#### Output

| Parameter | Description |
| --- | --- |
| `MembershipImpl` | Returned (modified) object containing the membership data. |

### Sample code

:::tip 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.

```swift
// Assumes a "ChatImpl" reference 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 memberships found")
    }
  } else {
    debugPrint("User not found")
  }
}
```

## Delete membership

Delete a membership with `delete()`.

### Method signature

This method takes the following parameters:

```swift
membership.delete() async throws
```

#### Input

This method doesn’t take any parameters.

#### Output

This method doesn’t return any value.

### Sample code

:::tip 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.
:::

```swift
// Assumes a "ChatImpl" reference 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 {
      try await membership.delete()
      debugPrint("Membership deleted")
    } else {
      debugPrint("No memberships found")
    }
  } else {
    debugPrint("User not found")
  }
}
```

Last updated at: 2026-09-30T07:20:08.000Z
