---
source_url: https://www.pubnub.com/docs/sdks/swift/api-reference/configuration
title: Configuration API for Swift Native SDK
updated_at: 2026-06-04T11:13:06.880Z
sdk_name: PubNub Swift SDK
sdk_version: 10.1.6
---

> 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


# Configuration API for Swift Native SDK

PubNub Swift SDK, use the latest version: 10.1.6

Install:

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

Use this configuration object to define how a PubNub instance behaves.

## Initializer(s)

Create a configuration with your Publish and Subscribe Keys.

:::warning Privacy
[MAU billing](https://www.pubnub.com/docs/general/setup/account-setup#pricing-model) tracks users ([Device](https://www.pubnub.com/docs/general/basics/identify-users-and-devices) and MAU) for analytics and billing. PubNub does not track customers using transactions with random UUIDs/UserIDs.
:::

### Method(s)

To initialize PubNub, use:

```swift
PubNubConfiguration(
  publishKey: String?,
  subscribeKey: String,
  userId: String,
  cryptoModule: CryptoModule? = nil,
  authKey: String? = nil,
  authToken: String? = nil,
  useSecureConnections: Bool = true,
  origin: String = "ps.pndsn.com",
  useInstanceId: Bool = false,
  useRequestId: Bool = false,
  automaticRetry: AutomaticRetry? = .default,
  durationUntilTimeout: UInt = 300,
  heartbeatInterval: UInt = 0,
  supressLeaveEvents: Bool = false,
  requestMessageCountThreshold: UInt = 100,
  filterExpression: String? = nil,
  enableEventEngine: Bool = true,
  maintainPresenceState: Bool = true
)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| publishKey | String? | Optional | `nil` | Specifies the PubNub Publish Key to be used when publishing messages to a channel. |
| subscribeKey | String | Yes | `nil` | Specifies the PubNub Subscribe Key to be used when subscribing to a channel. |
| userId | String | Yes |  | `userId` to use. You should set a unique identifier for the user or the device that connects to PubNub. It's a UTF-8 encoded string of up to 92 alphanumeric characters. If you don't set the `userId`, you won't be able to connect to PubNub. |
| cryptoModule | CryptoModule? | Optional | `nil` | The cryptography module used for encryption and decryption of messages and files. Takes the `cipherKey` parameter as argument. For more information, refer to the [cryptoModule](#cryptomodule) section. |
| authKey | String? | Optional | `nil` | If Access Manager is enabled, client will use `authKey` on all requests. |
| authToken | String? | Optional | `nil` | If Access Manager is enabled, client will use `authToken` instead of `authKey` on all requests. |
| useSecureConnections | Bool | Optional | `true` | If `true`, requests will be made over HTTPS; otherwise they will use HTTP (for cases when HTTPS might not be necessary or feasible, like development or testing purposes). You will still need to disable ATS for the system to allow insecure network traffic. See Apple's documentation for further details. |
| origin | String | Optional | `"ps.pndsn.com"` | Domain name used for requests. []() To request a custom domain, contact support and follow the [request process](https://www.pubnub.com/docs/general/setup/data-security#request-process). |
| useInstanceId | Bool | Optional | `false` | Whether a PubNub object `instanceId` should be included on outgoing requests. |
| useRequestId | Bool | Optional | `false` | Whether a request identifier should be included on outgoing requests. |
| automaticRetry | AutomaticRetry? | Optional | `ReconnectionPolicy.exponential (subscribe only)` | Custom reconnection configuration parameters. For more information, refer to the [automaticRetry](#automaticretry) section. |
| durationUntilTimeout | Int | Optional | `300` | Defines how long the server considers the client alive for presence. This property works similarly to the concept of long polling by sending periodic requests to the PubNub server every `300` seconds by default. These requests ensure the client remains active on subscribed channels. If no heartbeat is received within the timeout period, the client is marked inactive, triggering a "timeout" event on the [presence channel](https://www.pubnub.com/docs/general/presence/overview). Minimum value is `20`. |
| heartbeatInterval | UInt | Optional | `0` | Specifies how often the client will send heartbeat signals to the server. This property offers more granular control over client activity tracking than `durationUntilTimeout`. Configure this property to achieve a shorter presence timeout if needed, with the interval typically recommended to be `(durationUntilTimeout / 2) - 1`. The default value is `0` and it means that the SDK doesn't send explicit heartbeat messages to the server. Due to server constraints, don't set the value below `3` when configuring this parameter. |
| suppressLeaveEvents | Bool | Optional | `false` | Whether to send out the leave requests. |
| requestMessageCountThreshold | UInt | Optional | `100` | The number of messages into the payload before emitting `RequestMessageCountExceeded`. |
| filterExpression | String? | Optional | `nil` | PSV2 feature to subscribe with a custom filter expression. |
| enableEventEngine | Bool | Optional | `true` | Whether to use the recommended standardized workflows for subscribe and presence, optimizing how the SDK internally handles these operations and which [statuses](https://www.pubnub.com/docs/sdks/swift/status-events) it emits. |
| maintainPresenceState | Bool | Optional | `true` | This option works only when `enableEventEngine` is set to `true`. Whether the custom presence state information set using [pubnub.setPresence()](https://www.pubnub.com/docs/sdks/swift/api-reference/presence#set-state) should be sent every time the SDK sends a subscribe call. |
| cipherKey | Crypto? | Optional | `nil` | This way of setting this parameter is deprecated, pass it to `cryptoModule` instead. If set, all communication will be encrypted with this key. |
| uuid | String | Yes |  | This parameter is deprecated, use `userId` instead. UUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub. If you don't set the UUID, you won't be able to connect to PubNub. |

#### cryptoModule

`cryptoModule` encrypts and decrypts messages and files. From 6.1.0, you can choose the algorithms.

Each SDK includes two options: legacy 128-bit encryption and recommended 256-bit AES-CBC. For background, see [Message Encryption](https://www.pubnub.com/docs/general/setup/data-security#message-encryption) and [File Encryption](https://www.pubnub.com/docs/general/setup/data-security#file-encryption).

If you don't set `cryptoModule` and have `cipherKey` in PubNub config, the client uses legacy encryption.

For configuration details, utilities, and examples, see [Encryption](https://www.pubnub.com/docs/sdks/swift/api-reference/encryption).

:::note Legacy encryption with 128-bit cipher key entropy
You don't have to change your encryption configuration if you want to keep using the legacy encryption. If you want to use the recommended 256-bit AES-CBC encryption, you must explicitly set that in PubNub config.
:::

##### automaticRetry

`automaticRetry` lets the client retry requests automatically. It has these parameters:

| Parameter | Description |
| --- | --- |
| `retryLimit`Type: `UInt` | Maximum number of times a request can be retried before failing. |
| `policy`Type: `ReconnectionPolicy` | The policy to be used. Available values include: ReconnectionPolicy.linear(delay), ReconnectionPolicy.exponential(minDelay, maxDelay) `ReconnectionPolicy.exponential` is the default value for subscribe connections. |
| `retryableHTTPStatusCodes`Type: `Set<Int>` | One or more HTTP status codes for which the retry policy will be applied. |
| `retryableURLErrorCode`Type: `Set<URLError.Code>` | One or more URL error codes for which the retry policy will be applied. |
| `excluded`Type: `[AutomaticRetry.Endpoint]` | One or more [endpoints](https://github.com/pubnub/swift/blob/master/Sources/PubNub/Networking/Request/Operators/AutomaticRetry.swift) for which the retry policy won't be applied. |

For more information, refer to [SDK connection lifecycle](https://www.pubnub.com/docs/general/setup/connection-management#sdk-connection-lifecycle).

```swift
import PubNubSDK

/// Creates automatic retry behavior for failed requests with a linear backoff policy
/// The delay parameter (4 seconds) specifies the base linear delay between retry attempts.

/// As an example, we'll disable automatic retry for publish, signal, and fire requests.
/// Other possible values to exclude are:
/// - .messageSend
/// - .subscribe
/// - .presence
/// - .files
/// - .messageStorage
/// - .channelGroups
/// - .devicePushNotifications
/// - .appContext
/// - .messageActions
let automaticRetry = AutomaticRetry(
  policy: .linear(delay: 4),
  excluded: [.messageSend]
)

// Creates a PubNub instance with retry mechanism enabled
let pubnub = PubNub(
  configuration: PubNubConfiguration(
    publishKey: "demo",
    subscribeKey: "demo",
    userId: "myUniqueUserId",
    automaticRetry: automaticRetry
  )
)
```

#### Request configuration

Use `PubNub.RequestConfiguration` to customize one request without changing global settings.

| Parameter | Description |
| --- | --- |
| `customSession`Type: [SessionReplaceable?](#sessionreplaceable)Default: `nil` | A custom network session that implements the `SessionReplaceable` protocol, which provides session management capabilities including request routing, task execution, and session lifecycle control. |
| `customConfiguration`Type: [RouterConfiguration?](#routerconfiguration)Default: `nil` | The endpoint configuration used by the request. |
| `responseQueue`Type: [DispatchQueue](#dispatchqueue)Default: n/a | The queue that will be used for dispatching a response. |

##### SessionReplaceable

`SessionReplaceable` defines a custom network session interface. It manages routing, task execution, and the session lifecycle.

| Property | Description |
| --- | --- |
| `sessionID`Type: `UUID` | The unique identifier for the session object |
| `session`Type: `URLSessionReplaceable` | The underlying URLSession used to execute network tasks |
| `sessionQueue`Type: `DispatchQueue` | The dispatch queue used to execute session operations |
| `defaultRequestOperator`Type: `RequestOperator?` | The default request operator attached to every request (settable) |
| `sessionStream`Type: `SessionStream?` | Optional session stream for real-time communication (settable) |

##### RouterConfiguration

`RouterConfiguration` defines the base settings for PubNub endpoints. It includes authentication, connection security, encryption, and other behavior used to build and execute HTTP requests.

| Property | Description |
| --- | --- |
| `publishKey`Type: `String?` | Refer to the [publishKey](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#initializers) section. |
| `subscribeKey`Type: `String` | Refer to the [subscribeKey](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#initializers) section. |
| `uuid`Type: `String` | Unique device identifier for the client (equivalent to `userId` in Configuration) |
| `useSecureConnections`Type: `Bool` | Refer to the [useSecureConnections](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#initializers) section. |
| `origin`Type: `String` | Refer to the [origin](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#initializers) section. To request a custom domain, contact support and follow the [request process](https://www.pubnub.com/docs/general/setup/data-security#request-process). |
| `authKey`Type: `String?` | Refer to the [authKey](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#initializers) section. |
| `authToken`Type: `String?` | Refer to the [authToken](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#initializers) section. |
| `cryptoModule`Type: `CryptoModule?` | Refer to the [cryptoModule](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#cryptomodule) section. |
| `useRequestId`Type: `Bool` | Refer to the [useRequestId](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#initializers) section. |
| `consumerIdentifiers`Type: `[String: String]` | Key-value pairs identifying various consumers for request tracking |
| `enableEventEngine`Type: `Bool` | Refer to the [enableEventEngine](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#initializers) section. |
| `maintainPresenceState`Type: `Bool` | Refer to the [maintainPresenceState](https://www.pubnub.com/docs/sdks/swift/api-reference/configuration#initializers) section. |
| `urlScheme`Type: `String` | URL scheme derived from `useSecureConnections` ("`https`" or "`http`"). |
| `subscribeKeyExists`Type: `Bool` | Whether `subscribeKey` is valid and not empty. |
| `publishKeyExists`Type: `Bool` | Whether `publishKey` is valid and not empty. |

##### DispatchQueue

`DispatchQueue` specifies which queue handles response callbacks.

| Method | Description |
| --- | --- |
| `currentLabel`Type: `String` | Returns the label of the current `DispatchQueue` or "Unknown Queue" if no label was set |

:::note Official Apple Documentation
For standard `DispatchQueue` properties and methods, refer to [Apple's DispatchQueue documentation](https://developer.apple.com/documentation/dispatch/dispatchqueue).
:::

### Sample code

#### Initialize the PubNub client API

:::note Required User ID
Always set the `userId` to uniquely identify the user or device that connects to PubNub. This `userId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `userId`, you won't be able to connect to PubNub.
:::

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

// Create a configuration object with the desired parameters
let configuration = PubNubConfiguration(
  publishKey: "demo",
  subscribeKey: "demo",
  userId: "myUniqueUserId",
  heartbeatInterval: 100
)

// Creates a PubNub instance with the configuration specified above
let pubnub = PubNub(
  configuration: configuration
)
```

### Other examples

#### Initialization for a read-only client

If the client only reads and never publishes, set `publishKey` to `nil`:

:::note Required User ID
Always set the `userId` to uniquely identify the user or device that connects to PubNub. This `userId` should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the `userId`, you won't be able to connect to PubNub.
:::

```swift
let config = PubNubConfiguration(
  publishKey: nil,
  subscribeKey: "demo",
  userId: "myUniqueUserId"
)

let pubnub = PubNub(
  configuration: config
)
```

## Event listeners

PubNub SDKs provide several sources for real-time updates:

* The PubNub client can receive updates from all subscriptions: all channels, channel groups, channel metadata, and users.
* The [Subscription](https://www.pubnub.com/docs/sdks/swift/api-reference/publish-and-subscribe#create-a-subscription) object can receive updates only for the particular object for which it was created: channel, channel group, channel metadata, or user.
* The [SubscriptionsSet](https://www.pubnub.com/docs/sdks/swift/api-reference/publish-and-subscribe#create-a-subscription-set) object can receive updates for all objects for which a list of subscription objects was created.

To work with these sources, the SDK provides local representations of server entities, so you can subscribe and add handlers per entity. For details, see [Publish & Subscribe](https://www.pubnub.com/docs/sdks/swift/api-reference/publish-and-subscribe#event-listeners).

## Overriding PubNub configuration

You can change `PubNubConfiguration` properties until you set the configuration on a `PubNub` instance. After that, the settings are locked. To change them, create a new `PubNub` instance.

```swift
// Accessing the current configuration
var config = pubnub.configuration
// Modyfing user ID parameter
config.userId = "my_new_userId"
// Creating a new PubNub instance with the modified configuration
let newPubNub = PubNub(configuration: config)
```

### Filter

Update the filter expression without creating a new instance:

```swift
// snippet.hide
let configuration = PubNubConfiguration(
  publishKey: "demo",
  subscribeKey: "demo",
  userId: "myUniqueUserId"
)
let pubnub = PubNub(
  configuration: configuration
)
// snippet.show
pubnub.subscribeFilterExpression = "(senderID=='my_new_userId')"
```

## Terms in this document

* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.