Configuration API for Swift Native SDK
Use this configuration object to define how a PubNub instance behaves.
Initializer(s)
Create a configuration with your Publish and Subscribe Keys.
Privacy
MAU billing tracks users (Device and MAU) for analytics and billing. PubNub does not track customers using transactions with random UUIDs/UserIDs.
Method(s)
To initialize PubNub, use:
1PubNubConfiguration(
2  publishKey: String?,
3  subscribeKey: String,
4  userId: String,
5  cryptoModule: CryptoModule? = nil,
6  authKey: String? = nil,
7  authToken: String? = nil,
8  useSecureConnections: Bool = true,
9  origin: String = "ps.pndsn.com",
10  useInstanceId: Bool = false,
11  useRequestId: Bool = false,
12  automaticRetry: AutomaticRetry? = .default,
13  durationUntilTimeout: UInt = 300,
14  heartbeatInterval: UInt = 0,
15  supressLeaveEvents: Bool = false,
| Parameter | Description | 
|---|---|
| publishKeyType: String? Default: nil | Specifies the PubNub Publish Key to be used when publishing messages to a channel. | 
| subscribeKey*Type: String Default: nil | Specifies the PubNub Subscribe Key to be used when subscribing to a channel. | 
| userId*Type: String Default: n/a | userIdto 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. | 
| cryptoModuleType: CryptoModule? Default: nil | The cryptography module used for encryption and decryption of messages and files. Takes the cipherKeyparameter as argument.For more information, refer to the cryptoModule section. | 
| authKeyType: String? Default: nil | If Access Manager is enabled, client will use authKeyon all requests. | 
| authTokenType: String? Default: nil | If Access Manager is enabled, client will use authTokeninstead ofauthKeyon all requests. | 
| useSecureConnectionsType: Bool Default: 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. | 
| originType: String Default: "ps.pndsn.com" | Domain name used for requests. To request a custom domain, contact support and follow the request process. | 
| useInstanceIdType: Bool Default: false | Whether a PubNub object instanceIdshould be included on outgoing requests. | 
| useRequestIdType: Bool Default: false | Whether a request identifier should be included on outgoing requests. | 
| automaticRetryType: AutomaticRetry? Default: ReconnectionPolicy.exponential(subscribe only) | Custom reconnection configuration parameters. For more information, refer to the automaticRetry section. | 
| durationUntilTimeoutType: Int Default: 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 300seconds 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. Minimum value is 20. | 
| heartbeatIntervalType: UInt Default: 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 is0and it means that the SDK doesn't send explicit heartbeat messages to the server. Due to server constraints, don't set the value below3when configuring this parameter. | 
| suppressLeaveEventsType: Bool Default: false | Whether to send out the leave requests. | 
| requestMessageCountThresholdType: UInt Default: 100 | The number of messages into the payload before emitting RequestMessageCountExceeded. | 
| filterExpressionType: String? Default: nil | PSV2 feature to subscribe with a custom filter expression. | 
| enableEventEngineType: Bool Default: true | Whether to use the recommended standardized workflows for subscribe and presence, optimizing how the SDK internally handles these operations and which statuses it emits. | 
| maintainPresenceStateType: Bool Default: true | This option works only when enableEventEngineis set totrue.Whether the custom presence state information set using pubnub.setPresence()should be sent every time the SDK sends a subscribe call. | 
| cipherKeyType:  Default: nil | This way of setting this parameter is deprecated, pass it to cryptoModuleinstead. | 
| uuidType:  Default: n/a | This parameter is deprecated, use userIdinstead.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 and 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.
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 | 
|---|---|
| retryLimitType:  UInt | Maximum number of times a request can be retried before failing. | 
| policyType:  ReconnectionPolicy | The policy to be used. Available values include: 
 ReconnectionPolicy.exponentialis the default value for subscribe connections. | 
| retryableHTTPStatusCodesType:  Set<Int> | One or more HTTP status codes for which the retry policy will be applied. | 
| retryableURLErrorCodeType:  Set<URLError.Code> | One or more URL error codes for which the retry policy will be applied. | 
| excludedType:  [AutomaticRetry.Endpoint] | One or more endpoints for which the retry policy won't be applied. | 
For more information, refer to SDK connection lifecycle.
1
Request configuration
Use PubNub.RequestConfiguration to customize one request without changing global settings.
| Parameter | Description | 
|---|---|
| customSessionType:  SessionReplaceable?Default: nil | A custom network session that implements the SessionReplaceableprotocol, which provides session management capabilities including request routing, task execution, and session lifecycle control. | 
| customConfigurationType:  RouterConfiguration?Default: nil | The endpoint configuration used by the request. | 
| responseQueueType:  DispatchQueueDefault: 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 | 
|---|---|
| sessionIDType:  UUID | The unique identifier for the session object | 
| sessionType:  URLSessionReplaceable | The underlying URLSession used to execute network tasks | 
| sessionQueueType:  DispatchQueue | The dispatch queue used to execute session operations | 
| defaultRequestOperatorType:  RequestOperator? | The default request operator attached to every request (settable) | 
| sessionStreamType:  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 | 
|---|---|
| publishKeyType:  String? | Refer to the publishKey section. | 
| subscribeKeyType:  String | Refer to the subscribeKey section. | 
| uuidType:  String | Unique device identifier for the client (equivalent to userIdin Configuration) | 
| useSecureConnectionsType:  Bool | Refer to the useSecureConnections section. | 
| originType:  String | Refer to the origin section. To request a custom domain, contact support and follow the request process. | 
| authKeyType:  String? | Refer to the authKey section. | 
| authTokenType:  String? | Refer to the authToken section. | 
| cryptoModuleType:  CryptoModule? | Refer to the cryptoModule section. | 
| useRequestIdType:  Bool | Refer to the useRequestId section. | 
| consumerIdentifiersType:  [String: String] | Key-value pairs identifying various consumers for request tracking | 
| enableEventEngineType:  Bool | Refer to the enableEventEngine section. | 
| maintainPresenceStateType:  Bool | Refer to the maintainPresenceState section. | 
| urlSchemeType:  String | URL scheme derived from useSecureConnections("https" or "http"). | 
| subscribeKeyExistsType:  Bool | Whether subscribeKeyis valid and not empty. | 
| publishKeyExistsType:  Bool | Whether publishKeyis valid and not empty. | 
DispatchQueue
DispatchQueue specifies which queue handles response callbacks.
| Method | Description | 
|---|---|
| currentLabelType:  String | Returns the label of the current DispatchQueueor "Unknown Queue" if no label was set | 
Official Apple Documentation
For standard DispatchQueue properties and methods, refer to Apple's DispatchQueue documentation.
Sample code
Initialize the PubNub client API
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.
Reference code
1
Other examples
Initialization for a read-only client
If the client only reads and never publishes, set publishKey to nil:
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.
1
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 Subscriptionobject can receive updates only for the particular object for which it was created: channel, channel group, channel metadata, or user.
- The SubscriptionsSetobject 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.
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.
1
Filter
Update the filter expression without creating a new instance:
1