---
source_url: https://www.pubnub.com/docs/sdks/cocoa-swift/api-reference/configuration
title: Configuration API for Cocoa Swift SDK
updated_at: 2026-06-17T11:39:08.995Z
---

> 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 Cocoa Swift SDK

Complete API reference for building real-time applications on PubNub with the Swift Software Development Kit (SDK). This page covers configuration, initialization, and event handling with concise, working examples.

This SDK has been replaced by a PubNub Swift SDK written purely in Swift. See the [Swift SDK](https://www.pubnub.com/docs/sdks/swift).

## Configuration

`PNConfiguration` stores user-provided settings that define how the client behaves. The configuration includes properties to fine-tune the PubNub client.

### Method(s)

To create `configuration` instance you can use the following function in the Swift SDK:

```swift
public convenience init(publishKey: String, subscribeKey: String)
```

| Parameter | Type | Required | Default | Description |
| --- | --- | --- | --- | --- |
| publishKey | String | Yes |  | Your PubNub `Publish` Key. |
| subscribeKey | String | Yes |  | Your PubNub `Subscribe` Key. |
| heartbeatNotificationOptions | PNHeartbeatNotificationOptions | Optional |  | These are bitmask options, they can be combined. When client instances are notified about heartbeat operations, this happens through the `PNObjectEventListener` callback for statuses. `PNHeartbeatNotifySuccess`: explicitly tells client to notify on successful heartbeat operations. `PNHeartbeatNotifyFailure`: explicitly tells client to notify on failed heartbeat operations (default is only this option) `PNHeartbeatNotifyAll`: This is a combination of `PNHeartbeatNotifySuccess` and `PNHeartbeatNotifyFailure` `PNHeartbeatNotifyNone`: This means the client will not provide any callback notifications for heartbeat operations |
| stripMobilePayload | Bool | Optional |  | Stores whether client should strip out received messages (real-time and history) from data which has been appended by client (like mobile payload for mobile push notifications). |
| cipherKey | String | Optional |  | `Key` which is used to encrypt `messages` pushed to `PubNub` service and decrypt `messages` received from live feeds on which client subscribed at this moment. |
| subscribeMaximumIdleTime | TimeInterval | Optional |  | Maximum number of seconds which client should wait for events from live feed. Default `310`. |
| nonSubscribeRequestTimeout | TimeInterval | Optional |  | Number of seconds which is used by client during non-subscription operations to check whether response potentially failed with `timeout` or not. Default `10`. |
| presenceHeartbeatValue | Int | Optional |  | 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). |
| presenceHeartbeatInterval | Int | Optional |  | Specifies how often the client will send heartbeat signals to the server. This property offers more granular control over client activity tracking than `presenceHeartbeatValue`. Configure this property to achieve a shorter presence timeout if needed, with the interval typically recommended to be `(presenceHeartbeatValue / 2) - 1`. Due to server constraints, don't set the value below `3`. |
| keepTimeTokenOnListChange | Bool | Optional |  | Whether client should keep previous timetoken when subscribe on new set of remote data objects live feeds. Default `true`. |
| catchUpOnSubscriptionRestore | Bool | Optional |  | Whether client should try to catch up for events which occurred on previously subscribed remote data objects feed while client was off-line. Default `true`. |
| applicationExtensionSharedGroupIdentifier | String | Optional |  | Reference on group identifier which is used to share request cache between application extension and it's containing application. This property should be set to valid registered group only if `PubNub` client is used inside of application's extension (iOS 8.0+, macOS 10.10+). |
| requestMessageCountThreshold | UInt | Optional |  | Number of maximum expected messages from `PubNub` service in single response. |
| maximumMessagesCacheSize | UInt | Optional |  | Messages de-duplication cache size. Default `100`. |
| completeRequestsBeforeSuspension | Bool | Optional |  | Whether client should try complete all API call which is done before application will be completely suspended. Default `true`. |
| suppressLeaveEvents | Bool | Optional |  | If `true`, the client shouldn't send presence leave events during the unsubscribe process. |
| origin | String | Optional |  | If a custom domain is required, SDK accepts it here. To request a custom domain, contact support and follow the [request process](https://www.pubnub.com/docs/general/setup/data-security#request-process). |

### Sample code

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

```swift
let config = PNConfiguration(publishKey: "demo", subscribeKey: "demo")
self.client = PubNub.clientWithConfiguration(config)
self.client.addListener(self)
```

### Returns

Configured and ready to use client configuration instance.

### Other examples

#### Configure heartbeat notifications

##### PNConfiguration

```swift
let config = PNConfiguration(publishKey: "<pub key>", subscribeKey: "<sub key>")
/**
    This is where you need to adjust the PNConfiguration object for the types of heartbeat notifications you want.
    This is a bitmask of options located at https://github.com/pubnub/objective-c/blob/1f1c7a41a3bd8c32b644a6ad98fe179d45397c2b/PubNub/Misc/PNStructures.h#L24
    */
config.heartbeatNotificationOptions = [.notifyAll]

self.client = PubNub.clientWithConfiguration(config)
self.client.addListener(self)
```

##### Listener

```swift
func client(_ client: PubNub, didReceive status: PNStatus) {

    if status.operation == .heartbeatOperation {

        /**
            Heartbeat operations can in fact have errors, so it is important to check first for an error.
            For more information on how to configure heartbeat notifications through the status
            PNObjectEventListener callback, consult http://www.pubnub.com/docs/sdks/objective-c/api-reference/configuration#configuration_basic_usage
            */

        if !status.isError { /* Heartbeat operation was successful. */ }
        else { /* There was an error with the heartbeat operation, handle here. */ }
    }
}
```

## Configuration update

PubNub client instance doesn't allow dynamic configuration update, but it has helper functions which allow to receive new instance with updated configuration. Updated configuration will be applied on PubNub client copy. Original instance after copy block will return shouldn't be used anymore.

### Method(s)

To update client configuration you can use following functions in the Swift SDK:

#### Update client configuration with closure

```swift
open func copyWithConfiguration(
    _ configuration: PNConfiguration,
    completion block: @escaping (PubNub) -> Swift.Void
)
```

| Parameter | Description |
| --- | --- |
| `configuration` *Type: PNConfiguration | Class Instance which stores the configuration settings which is used by the PubNub client. |
| `closure` *Type: (PubNub) -> Void | Completion closure which is called at the end of update process, has one parameter - PubNub instance with updated configuration. |

#### Update client configuration with callback queue and closure

```swift
open func copyWithConfiguration(
    _ configuration: PNConfiguration,
    callbackQueue: DispatchQueue?,
    completion block: @escaping (PubNub) -> Swift.Void
)
```

| Parameter | Description |
| --- | --- |
| `configuration` *Type: PNConfiguration | Class Instance which stores the configuration settings which is used by the PubNub client. |
| `callbackQueue`Type: dispatch_queue_t | The GCD dispatch queue where callbacks and completion handlers will be called (asynchronously). |
| `closure` *Type: (PubNub) -> Void | Completion closure which is called at the end of update process, has one parameter - PubNub instance with updated configuration. |

### Sample code

Client configuration:

```swift
// User authorized and we need to update used UUID
let configuration = self.client.currentConfiguration()
configuration.uuid = "AuthorizedUserID"
self.client.copyWithConfiguration(configuration, completion: { (updatedClient) in

    // Store reference on new client with updated configuration.
    self.client = updatedClient
})
```

### Returns

Void

## Initialization

#### Include the SDK with CocoaPods

Install the CocoaPods gem by following the procedure defined in the [Getting Started guide](https://www.pubnub.com/docs/sdks/cocoa-swift). To add the PubNub SDK to your project with CocoaPods, there are four tasks to complete:

1. Create new Xcode project.
2. Create a Podfile in your newly created Xcode project root folder 1touch Podfile
3. The PubNub client can be added as module (only with a deployment target of OS X 10.9 and above) 1source 'https://github.com/CocoaPods/Specs.git'2platform :osx, "10.9"3use_frameworks!4 5target 'application-target-name' do6 pod "PubNub", "~> 4.1"7end If you have any other pods you'd like to include, or if you have other targets you'd to add (like a test target) add those entries to this Podfile as well. See the CocoaPods documentation for more information on Podfile configuration.
4. Install your pods by running pod install via the command line from the directory that contains your Podfile. Work within the workspaceAfter installing your Pods, work within the workspace generated by CocoaPods or specified by you in Podfile. Always open the newly generated workspace file, not the original project file.

#### OS x 10.9 and above: complete the application delegate configuration

If the project's deployment target is set to OS X 10.9 and above, you will need to import the module named `AppDelegate.swift`:

:::note Required UUID
Always set the `UUID` to uniquely identify the user or device that connects to PubNub. This `UUID` should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the `UUID` can significantly impact your billing if your account uses the [Monthly Active Users (MAUs)](https://www.pubnub.com/pricing/) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
:::

```swift
import Cocoa
import PubNubSDK // <- Here is our PubNub module import.
```

#### Common to all OS x versions: add the PNObjectEventListener protocol to the AppDelegate

```swift
class AppDelegate: NSObject, NSApplicationDelegate, PNObjectEventListener {

    // Stores reference on PubNub client to make sure what it won't be released.
    var client: PubNub!

    func applicationDidFinishLaunching(_ aNotification: Notification) {
        ...
    }
}
```

### Description

This function is used for initializing the PubNub Client API context. This function must be called before attempting to utilize any API functionality in order to establish account level credentials such as `publishKey` and `subscribeKey`.

### Method(s)

To `Initialize` PubNub you can use the following method(s) in the Swift SDK:

#### Initialize PubNub

```swift
open class func clientWithConfiguration(_ configuration: PNConfiguration) -> Self
```

| Parameter | Description |
| --- | --- |
| `configuration` *Type: PNConfiguration | Class Instance which stores the configuration settings which is used by the PubNub client. |

#### Initialize PubNub with callback queue

```swift
open class func clientWithConfiguration(
    _ configuration: PNConfiguration,
    callbackQueue: DispatchQueue?
) -> Self
```

| Parameter | Description |
| --- | --- |
| `configuration` *Type: PNConfiguration | Class Instance which stores the configuration settings which is used by the PubNub client. |
| `callbackQueue`Type: dispatch_queue_t | The GCD dispatch queue where callbacks and completion handlers will be called (asynchronously). |

### Sample code

#### Initialize the PubNub client API

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

```swift
let configuration = PNConfiguration(publishKey: "demo", subscribeKey: "demo")
configuration.TLSEnabled = true
self.client = PubNub.clientWithConfiguration(configuration)
```

### Returns

It returns the PubNub instance for invoking PubNub APIs like `publish()`, `subscribeToChannels()`, `historyForChannel`, `hereNowForChannel`.

### Other examples

#### Initialize the client

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

```swift
let configuration = PNConfiguration(publishKey: "demo", subscribeKey: "demo")
self.client = PubNub.clientWithConfiguration(configuration)
```

#### Initialization for a Read-Only client

In the case where a client will only read messages and never publish to a channel, you can simply omit the `publishKey` when initializing the client:

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

```swift
let configuration = PNConfiguration(publishKey: "", subscribeKey: "demo")
self.client = PubNub.clientWithConfiguration(configuration)
```

#### Use a custom UUID

Set a custom `UUID` to identify your users.

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

```swift
let configuration = PNConfiguration(publishKey: "myPublishKey", subscribeKey: "mySubscribeKey")
configuration.uuid = "myUniqueUUID"
self.client = PubNub.clientWithConfiguration(configuration)
```

#### Initializing with SSL enabled

This examples demonstrates how to enable PubNub Transport Layer Encryption with `SSL`. Just initialize the client with `ssl` set to `true`. The hard work is done, now the PubNub API takes care of the rest. Just subscribe and publish as usual and you are good to go.

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

```swift
let configuration = PNConfiguration(publishKey: "demo", subscribeKey: "demo")
configuration.TLSEnabled = true
self.client = PubNub.clientWithConfiguration(configuration)
```

## UUID

This function is used to set a user ID on the fly.

### Method(s)

To set `UUID` you can use the following method(s) in Swift SDK:

```swift
open var uuid: String
```

### Sample code

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

```swift
// User authorized and we need to update used UUID
let configuration = self.client.currentConfiguration()
configuration.uuid = NSUUID().uuidString
self.client.copyWithConfiguration(configuration, completion: { (updatedClient) in

    // Store reference on new client with updated configuration.
    self.client = updatedClient
})
```

### Other examples

#### Creating a function to subscribe a unique channel name

```swift
/**
    Subscription process results arrive to listener which should adopt to PNObjectEventListener protocol
    and registered using:
    */
self.client.addListener(self)
self.client.subscribeToChannels([NSUUID().uuidString], withPresence: false)

// Handle new message from one of channels on which client has been subscribed.
func client(_ client: PubNub, didReceiveMessage message: PNMessageResult) {

    // Handle new message stored in message.data.message
    if message.data.channel != message.data.subscription {

        // Message has been received on channel group stored in message.data.subscription.
    }
    else {

        // Message has been received on channel stored in message.data.channel.
    }

    print("Received message: \(message.data.message) on channel \(message.data.channel) " +
            "at \(message.data.timetoken)")
}

// Handle subscription status change.
func client(_ client: PubNub, didReceive status: PNStatus) {

    if status.operation == .subscribeOperation {

        // Check whether received information about successful subscription or restore.
        if status.category == .PNConnectedCategory || status.category == .PNReconnectedCategory {

            let subscribeStatus: PNSubscribeStatus = status as! PNSubscribeStatus
            if subscribeStatus.category == .PNConnectedCategory {

                // This is expected for a subscribe, this means there is no error or issue whatsoever.
            }
            else {

                /**
                    This usually occurs if subscribe temporarily fails but reconnects. This means there was
                    an error but there is no longer any issue.
                    */
            }
        }
        else if status.category == .PNUnexpectedDisconnectCategory {

            /**
                This is usually an issue with the internet connection, this is an error, handle
                appropriately retry will be called automatically.
                */
        }
        // Looks like some kind of issues happened while client tried to subscribe or disconnected from
        // network.
        else {

            let errorStatus: PNErrorStatus = status as! PNErrorStatus
            if errorStatus.category == .PNAccessDeniedCategory {

                /**
                    This means that Access Manager does allow this client to subscribe to this channel and channel group
                    configuration. This is another explicit error.
                    */
            }
            else {

                /**
                    More errors can be directly specified by creating explicit cases for other error categories
                    of `PNStatusCategory` such as: `PNDecryptionErrorCategory`,
                    `PNMalformedFilterExpressionCategory`, `PNMalformedResponseCategory`, `PNTimeoutCategory`
                    or `PNNetworkIssuesCategory`
                    */
            }
        }
    }
}
```

#### Initializing with a custom uuid

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

```swift
let configuration = self.client.currentConfiguration()
configuration.uuid = "myUniqueUUID"
self.client.copyWithConfiguration(configuration, completion: { (updatedClient) in

    // Store reference on new client with updated configuration.
    self.client = updatedClient
})
```

#### Creating a unique auth_key for Access Manager on initialization

```swift
let configuration = self.client.currentConfiguration()
configuration.authKey = NSUUID().uuidString
self.client.copyWithConfiguration(configuration, completion: { (updatedClient) in

    // Store reference on new client with updated configuration.
    self.client = updatedClient
})
```

## Authentication key

Setter and getter for users auth key.

### Method(s)

```swift
open var authKey: String?
```

### Sample code

#### Set auth key

```swift
let configuration = self.client.currentConfiguration()
configuration.authKey = "my_new_authkey"
self.client.copyWithConfiguration(configuration, completion: { (updatedClient) in

    // Store reference on new client with updated configuration.
    self.client = updatedClient
})
```

#### Get auth key

```swift
// Request current client configuration and pull out authorisation key from it.
let authKey = self.client.currentConfiguration().authKey
```

### Returns

`Get Auth key` returns the `current authentication key`.

## Filter expression

:::note Requires Stream Controller add-on
This method requires that the *Stream Controller* add-on is enabled for your key in the [Admin Portal](https://admin.pubnub.com/). Read the [support page](https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-) on enabling add-on features on your keys.
:::

To set or get message filters, you can use the following methods.

### Method(s)

```swift
open var filterExpression: String?
```

### Sample code

#### Set filter expression

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

```swift
let configuration = PNConfiguration(publishKey: "demo", subscribeKey: "demo")
self.client = PubNub.clientWithConfiguration(configuration)
self.client.filterExpression = "(senderID=='PubNub')";
```

#### Get filter expression

```swift
print("Filtering expression: \(self.client.filterExpression)")
```

### Returns

`Get Filter Expression` returns the `Current filtering expression`.

:::warning Malformed filter expression
If filter expression is malformed, `PNObjectEventListener` won't receive any messages and presence events from service (only error status).
:::

## 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.
