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.
Reuse the client instance
Create one PubNub client and reuse it for the lifetime of the user or session. Don't call PubNub(configuration:) for every publish or operation.
For more information, refer to Reuse the client instance.
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,
show all 20 linespublishKey#- Specifies the PubNub Publish Key to be used when publishing messages to a channel.
subscribeKeyrequired#- Specifies the PubNub Subscribe Key to be used when subscribing to a channel.
userIdrequired#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 theuserId, you won't be able to connect to PubNub.cryptoModule#- 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. authKey#- If Access Manager is enabled, client will use
authKeyon all requests. authToken#- If Access Manager is enabled, client will use
authTokeninstead ofauthKeyon all requests. useSecureConnections#- 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#- Domain name used for requests.
To request a custom domain, contact support and follow the request process. useInstanceId#- Whether a PubNub object
instanceIdshould be included on outgoing requests. useRequestId#- Whether a request identifier should be included on outgoing requests.
automaticRetry#- Custom reconnection configuration parameters.
For more information, refer to the automaticRetry section. durationUntilTimeout#- 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 is20. heartbeatInterval#- 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. suppressLeaveEvents#- Whether to send out the leave requests.
requestMessageCountThreshold#- The number of messages into the payload before emitting
RequestMessageCountExceeded. filterExpression#- PSV2 feature to subscribe with a custom filter expression.
enableEventEngine#- Whether to use the recommended standardized workflows for subscribe and presence, optimizing how the SDK internally handles these operations and which statuses it emits.
maintainPresenceState#- This option works only when
enableEventEngineis set totrue.
Whether the custom presence state information set usingpubnub.setPresence()should be sent every time the SDK sends a subscribe call. Deprecated#cipherKey- This way of setting this parameter is deprecated, pass it to
cryptoModuleinstead.
If set, all communication will be encrypted with this key. requiredDeprecated#uuid- This parameter is deprecated, use
userIdinstead.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 theUUID, you won't be able to connect to PubNub.
cryptoModule
cryptoModule encrypts and decrypts messages and files. From 6.2.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:
retryLimit#- Maximum number of times a request can be retried before failing.
policy#- The policy to be used.
Available values include:
ReconnectionPolicy.linear(delay)ReconnectionPolicy.exponential(minDelay, maxDelay)
ReconnectionPolicy.exponentialis the default value for subscribe connections. retryableHTTPStatusCodes#- One or more HTTP status codes for which the retry policy will be applied.
retryableURLErrorCode#- One or more URL error codes for which the retry policy will be applied.
For more information, refer to SDK connection lifecycle.
1
Request configuration
Use PubNub.RequestConfiguration to customize one request without changing global settings.
customSession#- A custom network session that implements the
SessionReplaceableprotocol, which provides session management capabilities including request routing, task execution, and session lifecycle control. customConfiguration#- The endpoint configuration used by the request.
responseQueue#- 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.
sessionID#- The unique identifier for the session object
session#- The underlying URLSession used to execute network tasks
sessionQueue#- The dispatch queue used to execute session operations
defaultRequestOperator#- The default request operator attached to every request (settable)
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.
publishKey#- Refer to the publishKey section.
subscribeKey#- Refer to the subscribeKey section.
uuid#- Unique device identifier for the client (equivalent to
userIdin Configuration) useSecureConnections#- Refer to the useSecureConnections section.
origin#- Refer to the origin section.
To request a custom domain, contact support and follow the request process. cryptoModule#- Refer to the cryptoModule section.
useRequestId#- Refer to the useRequestId section.
consumerIdentifiers#- Key-value pairs identifying various consumers for request tracking
enableEventEngine#- Refer to the enableEventEngine section.
maintainPresenceState#- Refer to the maintainPresenceState section.
urlScheme#- URL scheme derived from
useSecureConnections("https" or "http"). subscribeKeyExists#- Whether
subscribeKeyis valid and not empty. publishKeyExists#- Whether
publishKeyis valid and not empty.
DispatchQueue
DispatchQueue specifies which queue handles response callbacks.
currentLabel#- 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.
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