---
source_url: https://www.pubnub.com/docs/sdks/swift/api-reference/presence
title: Presence API for Swift Native SDK
updated_at: 2026-06-22T06:39:13.328Z
sdk_name: PubNub Swift SDK
sdk_version: 10.1.7
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Presence API for Swift Native SDK

PubNub Swift SDK, use the latest version: 10.1.7

Install:

```bash
Add PubNub via Swift Package Manager or CocoaPods@10.1.7
```

Presence lets you track who is online or offline and store custom state information. Presence shows:

* When a user has joined or left a channel
* How many users are subscribed to a particular channel (occupancy)
* Which channels a user or device is subscribed to
* Presence state associated with these users

Learn more about our Presence feature in the [Presence overview](https://www.pubnub.com/docs/general/presence/overview).

## Here now

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

This method returns information about the current state of a channel, including a list of unique user IDs (universally unique identifiers, UUIDs) currently subscribed to the channel and the total occupancy count of the channel.

:::note Cache
This method has a 3-second response cache time.
:::

### Method(s)

To call `Here Now` you can use the following method(s) in the Swift SDK:

```swift
func hereNow(
    on channels: [String],
    and groups: [String] = [],
    includeUUIDs: Bool = true,
    includeState: Bool = false,
    limit: Int = 1000,
    offset: Int = 0,
    custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
    completion: ((Result<[String: PubNubPresence], Error>) -> Void)?
)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| on | [String] | Yes |  | The list of `channels` to return occupancy results from. |
| and | [String] | Optional | `[]` | The list of `channel groups` for which will return occupancy results from. Wildcards are not supported. |
| includeUUIDs | Bool | Optional | `true` | Setting `uuid` to `false` disables the return of UUIDs. |
| includeState | Bool | Optional | `false` | Setting this flag to `true` will return the subscribe state information as well. |
| limit | Int | Optional | `1000` | Maximum number of occupants to return per channel. Valid range: `0-1000`. Use `0` to get occupancy counts without user details. |
| offset | Int | Optional | `0` | Zero-based starting index for pagination. Returns occupants starting from this position in the list. Must be `>= 0`. Requires `limit > 0`. Use with `limit` to paginate through large occupant lists. |
| custom | PubNub.RequestConfiguration | Optional | `PubNub.RequestConfiguration()` | An object that allows for per-request customization of PubNub Configuration or Network Session. |
| completion | ((Result<[String: | Optional | `nil` | The async `Result` of the method call. |

#### Completion handler result

##### Success

A `Dictionary` of channels mapped to their respective `PubNubPresence`

```swift
public protocol PubNubPresence {

    /// The channel identifier
    var channel: String { get }

    /// The total number of UUIDs present on the channel
    var occupancy: Int { get set }

    /// The known UUIDs present on the channel
    ///
    /// The `count` of this Array may differ from the `occupancy` field
    var occupants: [String] { get set }

    /// The Dictionary of UUIDs mapped to their respective presence state data
    var occupantsState: [String: JSONCodable] { get set }
}
```

##### Failure

An `Error` describing the failure.

### Sample code

#### Get a list of UUIDs subscribed to channel

:::tip Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
:::

```swift
import PubNubSDK

// Initializes a PubNub object with the configuration
let pubnub = PubNub(
  configuration: PubNubConfiguration(
    publishKey: "demo",
    subscribeKey: "demo",
    userId: "myUniqueUserId"
  )
)

// Get presence information for a channel
pubnub.hereNow(on: ["my_channel"]) { result in
  switch result {
  case let .success(presenceByChannel):
    print("Total channels: \(presenceByChannel.count)")
    print("Total occupancy across all channels: \(presenceByChannel.totalOccupancy)")

    if let myChannelPresence = presenceByChannel["my_channel"] {
      // Print the occupancy for the channel
      print("The occupancy for `my_channel` is \(myChannelPresence.occupancy)")
      // Iterating over each occupant in the channel and printing their UUID
      myChannelPresence.occupants.forEach { occupant in
        print("Occupant UUID: \(occupant)")
      }
    }
  case let .failure(error):
    print("Failed hereNow Response: \(error.localizedDescription)")
  }
}
```

### Other examples

#### Return occupancy only

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

You can return only the `occupancy` information for a single channel by specifying the channel and setting `UUIDs` to false:

```swift
// Get presence information for a channel without UUIDs
pubnub.hereNow(
  on: ["my-channel"],
  includeUUIDs: false
) { result in
  switch result {
  case let .success(presenceByChannel):
    if let myChannelPresence = presenceByChannel["my_channel"] {
      print("The occupancy for `my_channel` is \(myChannelPresence.occupancy)")
    }
  case let .failure(error):
    print("Failed hereNow Response: \(error.localizedDescription)")
  }
}
```

#### Channel group usage

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

```swift
// Get presence information for a channel group
pubnub.hereNow(
  on: [],
  and: ["my-channel-group"]
) { result in
  switch result {
  case let .success(presenceByChannel):
    print("The `Dictionary` of channels mapped to their respective `PubNubPresence`: \(presenceByChannel)")
  case let .failure(error):
    print("Failed hereNow Response: \(error.localizedDescription)")
  }
}
```

## Where now

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

This method returns the list of channels a UUID is subscribed to.

:::note Timeout events
If the app restarts (or the page refreshes) within the heartbeat window, no timeout event is generated.
:::

### Method(s)

To call `whereNow()` you can use the following method(s) in the Swift SDK:

```swift
func whereNow(
    for uuid: String,
    custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
    completion: `((Result<[String: [String]], Error>) -> Void)?`
)
```

| Parameter | Description |
| --- | --- |
| `for` *Type: StringDefault: n/a | Specifies the `UUID` to return channel list for. |
| `custom`Type: [PubNub.RequestConfiguration](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#request-configuration)Default: `PubNub.RequestConfiguration()` | An object that allows for per-request customization of PubNub configuration or network session. For more information, refer to the [Request Configuration](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#request-configuration) section. |
| `completion`Type: `((Result<[String: [String]], Error>) -> Void)?`Default: `nil` | The async `Result` of the method call. |

#### Completion handler result

##### Success

A `Dictionary` of UUIDs mapped to their respective `Array` of channels they have presence on.

##### Failure

An `Error` describing the failure.

### Sample code

You simply need to define the `uuid` and the `callback` function to be used to send the data to as in the example below.

#### Get a list of channels a UUID is subscribed to

```swift
// Get the channels that a specific UUID is present on
pubnub.whereNow(for: "my-unique-uuid") { result in
  switch result {
  case let .success(channelsByUUID):
    print("A `Dictionary` of UUIDs mapped to their respective `Array` of channels they have presence on \(channelsByUUID)")
    if let channels = channelsByUUID["my-unique-uuid"] {
      print("The list of channel identifiers for the UUID `my-unique-uuid`: \(channels)")
    }
  case let .failure(error):
    print("Failed WhereNow Response: \(error.localizedDescription)")
  }
}
```

## User state

:::warning Requires Presence
This method requires that the Presence add-on is [enabled](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) for your key in the [Admin Portal](https://admin.pubnub.com/). For information on how to receive presence events and what those events are, refer to [Presence Events](https://www.pubnub.com/docs/general/presence/presence-events#subscribe-to-presence-channel).
:::

Clients can set a dynamic custom state (score, game state, location) for their users on one or more channels and store it on a channel as long as the user stays subscribed.

The state is not persisted, and when the client disconnects, the state data is lost. For more information, refer to [Presence State](https://www.pubnub.com/docs/general/presence/presence-state).

### Method(s)

#### Set state

```swift
func setPresence(
    state: [String: JSONCodableScalar],
    on channels: [String],
    and groups: [String] = [],
    custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
    completion: ((Result<JSONCodable, Error>) -> Void)?
)
```

| Parameter | Description |
| --- | --- |
| `state` *Type: [String: JSONCodableScalar]Default: n/a | The `state` Dictionary to store. Nesting of Dictionary values isn't permitted, and key names beginning with prefix `pn` are reserved. Setting the `state` will overwrite the previous values set. Clearing out the `state` involves passing in an empty Dictionary. |
| `on`Type: [String]Default: n/a | The list of channel to set the state on. Pass an empty array to not set. |
| `and`Type: [String]Default: n/a | The list of channel groups to set the state on. |
| `custom`Type: [PubNub.RequestConfiguration](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#request-configuration)Default: `PubNub.RequestConfiguration()` | An object that allows for per-request customization of PubNub configuration or network session. For more information, refer to the [Request Configuration](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#request-configuration) section. |
| `completion`Type: `((Result<JSONCodable, Error>) -> Void)?`Default: `nil` | The async `Result` of the method call. |

#### Completion handler result

##### Success

The presence State set as a `JSONCodable`.

##### Failure

An `Error` describing the failure.

#### Get state

```swift
func getPresenceState(
    for uuid: String,
    on channels: [String],
    and groups: [String] = [],
    custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
    completion: ((Result<(uuid: String, stateByChannel: [String: JSONCodable]), Error>) -> Void)?
)
```

| Parameter | Description |
| --- | --- |
| `for` *Type: StringDefault: n/a | The UUID to retrieve the state for. |
| `on`Type: [String]Default: n/a | The list of channel to get the state on. Pass an empty array to not get. |
| `and`Type: [String]Default: [] | The list of channel groups to get the state on. Pass an empty array to not get. |
| `custom`Type: [PubNub.RequestConfiguration](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#request-configuration)Default: `PubNub.RequestConfiguration()` | An object that allows for per-request customization of PubNub configuration or network session. For more information, refer to the [Request Configuration](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#request-configuration) section. |
| `completion`Type: `((Result<(uuid: String, stateByChannel: [String: JSONCodable]), Error>) -> Void)?`Default: `nil` | The async `Result` of the method call. |

#### Completion handler result

##### Success

A `Tuple` containing the UUID that set the State and a `Dictionary` of channels mapped to their respective State.

##### Failure

An `Error` describing the failure.

### Sample code

#### Set state

```swift
// Set the presence state for a channel and channel group
pubnub.setPresence(
  state: ["new": "state"],
  on: ["channelSwift"],
  and: ["demo"]
) { result in
  switch result {
  case let .success(presenceSet):
    print("The presence State set as a `JSONCodable`: \(presenceSet)")
  case let .failure(error):
    print("Failed Set State Response: \(error.localizedDescription)")
  }
}
```

#### Get state

```swift
// Get the presence state for a channel and channel group
pubnub.getPresenceState(
  for: pubnub.configuration.uuid,
  on: ["channelSwift"],
  and: ["demo"]
) { result in
  switch result {
  case let .success(uuid, stateByChannel):
    print("The UUID `\(uuid)` has the following presence state \(stateByChannel)")
  case let .failure(error):
    print("Failed Get State Response: \(error.localizedDescription)")
  }
}
```

### Other examples

#### Converting the response to a JSON dictionary

```swift
// Get the presence state for a channel and decode it into a Dictionary type
pubnub.setPresence(
  state: ["new": "state"],
  on: ["channelSwift"]
) { result in
  switch result {
  case let .success(presenceSet):
    print("The String value for `New` is: \(presenceSet.codableValue[rawValue: "new"] as? String)")
  case let .failure(error):
    print("Failed Set State Response: \(error.localizedDescription)")
  }
}
```

#### Converting the response to a custom object

```swift
// Declares the type to decode the state value into
struct MyPresenceState: JSONCodable {
  var new: String
}

// Set the presence state for a channel and decode it into a custom type
pubnub.setPresence(
  state: ["new": "state"],
  on: ["channelSwift"]
) { result in
  switch result {
  case let .success(presenceSet):
    print("The Object representation is: \(try? presenceSet.codableValue.decode(MyPresenceState.self))")
  case let .failure(error):
    print("Failed Set State Response: \(error.localizedDescription)")
  }
}
```