Configuration API for Objective-C SDK
Complete API reference for building real-time applications on PubNub with the Objective-C Software Development Kit (SDK). This page covers configuration, initialization, and event handling with concise, working examples.
Configuration
PNConfiguration stores settings that control the client's behavior. It includes credentials and options to tailor how the client connects, retries, and processes messages.
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)
Create a configuration instance with:
1+ (instancetype)configurationWithPublishKey:(NSString *)publishKey
2 subscribeKey:(NSString *)subscribeKey;
3 userID:(NSString *)userID
| Parameter | Description |
|---|---|
publishKey *Type: NSString | Publish key. Example: "demo". |
subscribeKey *Type: NSString | Subscribe key. Example: "demo". |
userID *Type: NSString | User ID. UTF‑8 string, up to 92 characters. Required. |
heartbeatNotificationOptionsType: PNHeartbeatNotificationOptions | Heartbeat notifications. Success, Failure (default), All, or None. |
stripMobilePayloadType: BOOL | If YES, remove push payload metadata (APNs/FCM) from received messages. |
subscribeMaximumIdleTimeType: NSTimeInterval | Max seconds to wait for events. Default: 310. |
nonSubscribeRequestTimeoutType: NSTimeInterval | Timeout for non‑subscribe ops, in seconds. Default: 10. |
presenceHeartbeatValueType: NSInteger | Presence timeout (seconds). Defaults to 300. Triggers timeout if no heartbeat. |
presenceHeartbeatIntervalType: NSInteger | Heartbeat interval (seconds). Typical: (presenceHeartbeatValue / 2) - 1. Min 3. |
keepTimeTokenOnListChangeType: BOOL | Keep previous timetoken on subscribe list change. Default: YES. |
catchUpOnSubscriptionRestoreType: BOOL | Catch up on missed events after restore. Default: YES. |
applicationExtensionSharedGroupIdentifierType: NSString | Shared App Group ID for extensions (iOS 8.0+, macOS 10.10+). |
requestMessageCountThresholdType: NSUInteger | Max messages per response before PNRequestMessageCountExceededCategory. |
maximumMessagesCacheSizeType: NSUInteger | De‑duplication cache size. Default: 100. |
completeRequestsBeforeSuspensionType: BOOL | Finish in‑flight API calls before suspension. Default: YES. |
suppressLeaveEventsType: BOOL | If YES, don’t send presence leave events on unsubscribe. |
originType: NSString | Custom origin (domain). Example: "ps.pndsn.com". |
requestRetryType: PNRequestRetryConfiguration | Retry policy settings. See requestRetry. |
cryptoModuleType: [PNCryptoModule AESCBCCryptoModuleWithCipherKey: NSString randomInitializationVector: BOOL];[PNCryptoModule legacyCryptoModuleWithCipherKey: NSString randomInitializationVector: BOOL]; | Encrypt/decrypt module. Takes cipherKey and useRandomInitializationVector. See cryptoModule. |
logLevelType: PNLogLevel | Minimum log level to capture. Values: PNNoneLogLevel (disabled), PNTraceLogLevel, PNDebugLogLevel, PNInfoLogLevel, PNWarnLogLevel, PNErrorLogLevel. Default: PNNoneLogLevel. See Logging. |
enableDefaultConsoleLoggerType: BOOL | Enable the built-in console logger. Default: YES. When YES, log entries print to the Xcode console. When NO, the SDK uses only custom loggers. See Logging. |
loggersType: NSArray<id<PNLogger>> | Array of custom logger implementations conforming to the PNLogger protocol. Custom loggers receive log entries alongside the built-in console logger if the console logger is enabled. See Custom Loggers. |
cipherKeyType: | This way of setting this parameter is deprecated, pass it to cryptoModule instead. 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. |
useRandomInitializationVectorType: | This way of setting this parameter is deprecated, pass it to cryptoModule instead. YES the initialization vector (IV) is random for all requests (not just for file upload). When NO the IV is hard-coded for all requests except for file upload. By default, using the random initialization vector is enabled. |
Disabling random initialization vector
Disable random initialization vector (IV) only for backward compatibility (<4.16.0) with existing applications. Never disable random IV on new applications.
requestRetry
Use PNRequestRetryConfiguration to control retry behavior. For policy details, see Reconnection Policy.
Create a default linear retry policy
1+ (instancetype)configurationWithLinearDelay;
Example
1configuration.requestRetry = [PNRequestRetryConfiguration configurationWithLinearDelay];
Create a linear retry policy with excluded endpoints
1+ (instancetype)configurationWithLinearDelayExcludingEndpoints:(PNEndpoint)endpoints, ...;
| Parameter | Description |
|---|---|
endpointsType: PNEndpoint | The endpoints to exclude. For a list of endpoints, inspect NS_ENUM(NSUInteger, PNEndpoint) in the PNStructures file. |
Example
1configuration.requestRetry = [PNRequestRetryConfiguration configurationWithLinearDelayExcludingEndpoints:PNMessageSendEndpoint, 0];
Create a linear retry policy with excluded endpoints and custom parameters
1+ (instancetype)configurationWithLinearDelay:(NSTimeInterval)delay
2 maximumRetry:(NSUInteger)maximumRetry
3 excludedEndpoints:(PNEndpoint)endpoints, ...;
| Parameter | Description |
|---|---|
delayType: NSTimeInterval | Delay in seconds between failed requests. |
maximumRetryType: NSUInteger | How many times to retry before throwing an error. |
excludedEndpointsType: PNEndpoint | The endpoints to exclude. For a list of endpoints, inspect NS_ENUM(NSUInteger, PNEndpoint) in the PNStructures file. |
Example
1/// example
2configuration.requestRetry = [PNRequestRetryConfiguration configurationWithLinearDelay:3.f
3 maximumRetry:3
4 excludedEndpoints:PNMessageSendEndpoint, PNMessageStorageEndpoint, 0];
Create a default exponential retry policy
1+ (instancetype)configurationWithExponentialDelay;
Example
1configuration.requestRetry = [PNRequestRetryConfiguration configurationWithExponentialDelay];
Create an exponential retry policy with excluded endpoints
1+ (instancetype)configurationWithExponentialDelayExcludingEndpoints:(PNEndpoint)endpoints, ...;
| Parameter | Description |
|---|---|
endpointsType: PNEndpoint | The endpoints to exclude. For a list of endpoints, inspect NS_ENUM(NSUInteger, PNEndpoint) in the PNStructures file. |
Example
1configuration.requestRetry = [PNRequestRetryConfiguration configurationWithExponentialDelayExcludingEndpoints:PNMessageSendEndpoint, 0];
Create an exponential retry policy with excluded endpoints and custom parameters
1+ (instancetype)configurationWithExponentialDelay:(NSTimeInterval)minimumDelay
2 maximumDelay:(NSTimeInterval)maximumDelay
3 maximumRetry:(NSUInteger)maximumRetry
4 excludedEndpoints:(PNEndpoint)endpoints, ...;
| Parameter | Description |
|---|---|
minimumDelayType: NSTimeInterval | Base delay in seconds used to calculate the next delay. |
maximumDelayType: NSTimeInterval | Maximum allowed computed delay in seconds between retry attempts. |
maximumRetryType: NSUInteger | How many times to retry before throwing an error. |
excludedEndpointsType: PNEndpoint | The endpoints to exclude. For a list of endpoints, inspect NS_ENUM(NSUInteger, PNEndpoint) in the PNStructures file. |
Example
configuration.requestRetry = [PNRequestRetryConfiguration configurationWithExponentialDelay:3.f
maximumDelay:120.f
maximumRetry:3
excludedEndpoints:PNMessageSendEndpoint, PNMessageStorageEndpoint, 0];
cryptoModule
cryptoModule encrypts and decrypts messages and files. From 5.1.3, you can configure the algorithms it uses.
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 but set cipherKey and useRandomInitializationVector in config, the client uses legacy encryption.
For configuration details 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.
Sample code
Required User ID
Always set the User ID (userID) to uniquely identify the user or device that connects to PubNub. Persist the value and keep it stable for the lifetime of the user or device. If you don't set the userID, the client cannot connect.
1// Basic configuration
2PNConfiguration *config = [PNConfiguration configurationWithPublishKey:@"demo"
3 subscribeKey:@"demo"
4 userID:@"myUniqueUserID"];
5
6// Create a PubNub client instance
7PubNub *client = [PubNub clientWithConfiguration:config];
8
9// Add listener for PubNub events
10[client addListener:self];
11
12// Subscribe to a test channel
13PNSubscribeRequest *subscribeRequest = [PNSubscribeRequest requestWithChannels:@[@"test-channel"]
14 channelGroups:nil];
15subscribeRequest.observePresence = YES;
show all 51 linesReturns
Returns a configured client configuration instance.
Other examples
Configure logging
Enable logging to monitor SDK (Software Development Kit) activity and troubleshoot issues.
Basic logging configuration
1PNConfiguration *config = [PNConfiguration configurationWithPublishKey:@"demo"
2 subscribeKey:@"demo"
3 userID:@"myUniqueUserID"];
4
5// Set minimum log level
6config.logLevel = PNDebugLogLevel;
7
8PubNub *client = [PubNub clientWithConfiguration:config];
Change log level at runtime
1// Adjust logging detail after initialization
2[client setLogLevel:PNErrorLogLevel];
Disable console logger
1PNConfiguration *config = [PNConfiguration configurationWithPublishKey:@"demo"
2 subscribeKey:@"demo"
3 userID:@"myUniqueUserID"];
4config.logLevel = PNDebugLogLevel;
5config.enableDefaultConsoleLogger = NO; // Disable default logger output to the Xcode console
6
7PubNub *client = [PubNub clientWithConfiguration:config];
Add custom loggers
1PNConfiguration *config = [PNConfiguration configurationWithPublishKey:@"demo"
2 subscribeKey:@"demo"
3 userID:@"myUniqueUserID"];
4config.logLevel = PNDebugLogLevel;
5config.loggers = @[myCustomLogger]; // Add your PNLogger implementation
6
7PubNub *client = [PubNub clientWithConfiguration:config];
For custom logger implementation examples and best practices, see Logging.
Configure heartbeat notifications
PNConfiguration
1PNConfiguration *config = [PNConfiguration configurationWithPublishKey:@"<pub key>" subscribeKey:@"<sub key>"];
2/**
3 This is where you need to adjust the PNConfiguration object for the types of heartbeat notifications you want.
4 This is a bitmask of options located at https://github.com/pubnub/objective-c/blob/1f1c7a41a3bd8c32b644a6ad98fe179d45397c2b/PubNub/Misc/PNStructures.h#L24
5 */
6config.heartbeatNotificationOptions = PNHeartbeatNotifyAll;
7
8self.client = [PubNub clientWithConfiguration:config];
9[self.client addListener:self];
Listener
1- (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status {
2
3 if (status.operation == PNHeartbeatOperation) {
4
5 /**
6 Heartbeat operations can in fact have errors, so it is important to check first for an error.
7 For more information on how to configure heartbeat notifications through the status
8 PNObjectEventListener callback, consult http://www.pubnub.com/docs/sdks/objective-c/api-reference/configuration#configuration_basic_usage
9 */
10
11 if (!status.isError) { /* Heartbeat operation was successful. */ }
12 else { /* There was an error with the heartbeat operation, handle here. */ }
13 }
14}
Initialization
Install CocoaPods and follow the Getting Started guide. Then:
-
Create a new Xcode project.
-
Create a Podfile in a new Xcode project root folder
1pod init1platform :ios, '9.0'
2
3target 'application-target-name' do
4 use_frameworks!
5
6 pod "PubNub", "~> 4"
7end
If you need more pods or targets (for example, a test target), add them to the same Podfile. See the CocoaPods documentation for details.
- Install your pods by running
pod installvia the command line from the directory that contains your Podfile.
Note
After installing your Pods, you should only be working within the workspace generated by CocoaPods or specified by you in Podfile. Always open the newly generated workspace file, not the original project file!
Import the SDK headers where you use them:
1#import <PubNub/PubNub.h>
Complete application delegate configuration
Add the PNObjectEventListener protocol to AppDelegate in the implementation file's anonymous category:
Required User ID
Always set the User ID (userID) to uniquely identify the user or device that connects to PubNub. Persist the value and keep it stable for the lifetime of the user or device. If you don't set the userID, the client cannot connect.
1#import <PubNub/PubNub.h>
2
3@interface AppDelegate () <PNObjectEventListener>
4
5// Stores reference on PubNub client to make sure what it won't be released.
6@property (nonatomic, strong) PubNub *client;
7
8@end
Description
Initialize the client API before calling any SDK methods. This sets account-level credentials such as publishKey and subscribeKey.
Method(s)
Initialize PubNub with:
Initialize PubNub
1+ (instancetype)clientWithConfiguration:(PNConfiguration *)configuration;
| Parameter | Description |
|---|---|
configuration *Type: PNConfiguration | Reference on instance which store all user-provided information about how client should operate and handle events. |
Initialize with callback queue
1+ (instancetype)clientWithConfiguration:(PNConfiguration *)configuration callbackQueue:(dispatch_queue_t)callbackQueue;
| Parameter | Description |
|---|---|
configuration *Type: PNConfiguration | Reference on instance which store all user-provided information about how client should operate and handle events. |
callbackQueueType: dispatch_queue_t | Reference on queue which should be used by client for completion block and delegate calls. |
Sample code
Initialize the PubNub client API
Required User ID
Always set the User ID (userID) to uniquely identify the user or device that connects to PubNub. Persist the value and keep it stable for the lifetime of the user or device. If you don't set the userID, the client cannot connect.
1PNConfiguration *config = [PNConfiguration configurationWithPublishKey:@"demo"
2 subscribeKey:@"demo"
3 userID:@"myUserID"];
4config.TLSEnabled = YES;
5self.client = [PubNub clientWithConfiguration:configuration];
Configuration instance
Ensure the same configuration instance (config) is passed to clientWithConfiguration: that you created above. The TLSEnabled property refers to Transport Layer Security (TLS).
Returns
Returns the client instance for invoking APIs such as publish, subscribeToChannels, historyForChannel, and hereNowForChannel.
Other examples
Initialize the client
Required User ID
Always set the User ID (userID) to uniquely identify the user or device that connects to PubNub. Persist the value and keep it stable for the lifetime of the user or device. If you don't set the userID, the client cannot connect.
1PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo"
2 subscribeKey:@"demo"
3 userID:@"myUserID"];
4
5self.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:
Required User ID
Always set the User ID (userID) to uniquely identify the user or device that connects to PubNub. Persist the value and keep it stable for the lifetime of the user or device. If you don't set the userID, the client cannot connect.
1PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@""
2 subscribeKey:@"demo"
3 userID:@"myUserID"];
4self.client = [PubNub clientWithConfiguration:configuration];
Event listeners
Use listeners to receive connectivity, message, presence, object, and file events. Add listeners before you subscribe or publish.
Add listeners
Your listener class must conform to the PNEventsListener protocol to receive callbacks.
1// Adding listener.
2[pubnub addListener:self];
3
4// Callbacks listed below.
5
6- (void)client:(PubNub *)pubnub didReceiveMessage:(PNMessageResult *)message {
7 NSString *channel = message.data.channel; // Channel on which the message has been published
8 NSString *subscription = message.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
9 NSNumber *timetoken = message.data.timetoken; // Publish timetoken
10 id msg = message.data.message; // Message payload
11 NSString *publisher = message.data.publisher; // Message publisher
12}
13
14- (void)client:(PubNub *)pubnub didReceiveSignal:(PNSignalResult *)signal {
15 NSString *channel = message.data.channel; // Channel on which the signal has been published
show all 102 linesRemove listeners
1[pubnub removeListener:self]
Objective-C statements
Objective-C statements require a trailing semicolon in implementation files.
Handling disconnects
The SDK automatically reconnects and reports status. You can stop automatic retries.
1- (void)client:(PubNub *)pubnub didReceiveStatus:(PNStatus *)status {
2 if (status.isError && status.willAutomaticallyRetry) {
3 // Stop automatic retry attempts.
4 [status cancelAutomaticRetry];
5 }
6}
Listener status events
| Category | Description |
|---|---|
PNAcknowledgmentCategory | An API call was successful. This status has additional details based on the type of the successful operation. |
PNAccessDeniedCategory | Access Manager permission failure. |
PNTimeoutCategory | Server didn't respond in time for reported operation request. |
PNNetworkIssuesCategory | No internet connection. |
PNRequestMessageCountExceededCategory | Reported when received message count exceeds requestMessageCountThreshold. |
PNConnectedCategory | The SDK subscribed to new channels / channel groups. |
PNReconnectedCategory | The SDK was able to reconnect to PubNub. |
PNDisconnectedCategory | The SDK unsubscribed from channels / channel groups. |
PNUnexpectedDisconnectCategory | Unexpected loss of live updates from PubNub. |
PNRequestURITooLongCategory | Request URI too long (too many channels or channel groups). |
PNMalformedFilterExpressionCategory | Malformed filtering expression. |
PNMalformedResponseCategory | Unexpected service response. |
PNDecryptionErrorCategory | Decryption failed using the configured cipherKey. |
PNTLSConnectionFailedCategory | Secure (TLS) connection failed. |
PNTLSUntrustedCertificateCategory | Untrusted certificate chain. |
UserID
Set the user ID at runtime.
Method(s)
1@property (nonatomic, copy, setter = setUserID:) NSString *userID;
Sample code
Required User ID
Always set the User ID (userID) to uniquely identify the user or device that connects to PubNub. Persist the value and keep it stable for the lifetime of the user or device. If you don't set the userID, the client cannot connect.
1// User authorized and we need to update used UUID
2PNConfiguration *configuration = self.client.currentConfiguration;
3configuration.userID = @"myUniqueUserID";
4
5__weak __typeof(self) weakSelf = self;
6[self.client copyWithConfiguration:configuration completion:^(PubNub *client) {
7
8 weakSelf.client = client;
9}];
Other examples
Creating a function to subscribe a unique channel name
1/**
2 Subscription process results arrive to listener which should adopt to
3 PNObjectEventListener protocol and registered using:
4 */
5[self.client addListener:self];
6[self.client subscribeToChannels:@[[NSUUID UUID].UUIDString] withPresence:NO];
7
8// Handle new message from one of channels on which client has been subscribed.
9- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {
10
11 // Handle new message stored in message.data.message
12 if (![message.data.channel isEqualToString:message.data.subscription]) {
13
14 // Message has been received on channel group stored in message.data.subscription.
15 }
show all 77 linesCreating a unique auth_key for Access Manager on initialization
1PNConfiguration *configuration = self.client.currentConfiguration;
2configuration.authKey = [NSUUID UUID].UUIDString.lowercaseString;
3
4__weak __typeof(self) weakSelf = self;
5[self.client copyWithConfiguration:configuration completion:^(PubNub *client) {
6
7 // Store reference on new client with updated configuration.
8 weakSelf.client = client;
9}];
Authentication key
Set and get the auth key.
Method(s)
Authentication key
1@property (nonatomic, nullable, copy) NSString *authKey;
UserID
1@property (nonatomic, copy, setter = setUserID:) NSString *userID;
Sample code
Set auth key
1PNConfiguration *configuration = self.client.currentConfiguration;
2configuration.authKey = @"my_new_authkey";
3
4__weak __typeof(self) weakSelf = self;
5[self.client copyWithConfiguration:configuration completion:^(PubNub *client) {
6
7 // Store reference on new client with updated configuration.
8 weakSelf.client = client;
9}];
Get auth key
1// Request current client configuration and pull out authorisation key from it.
2NSString *authorizationKey = self.client.currentConfiguration.authKey;
Returns
Get Auth key returns the current authentication key.
Filter expression
Requires Stream Controller add-on
This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
Stream filtering lets a subscriber receive only messages that match the filter. The filter runs on the server, so non‑matching messages never reach the client.
Use the following property to set or get the filter. For details, see Publish Messages.
Method(s)
1@property (nonatomic, nullable, copy) NSString *filterExpression;
Sample code
Set filter expression
Required User ID
Always set the User ID (userID) to uniquely identify the user or device that connects to PubNub. Persist the value and keep it stable for the lifetime of the user or device. If you don't set the userID, the client cannot connect.
1PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo"
2 subscribeKey:@"demo"
3 userID:@"myUserID"];
4self.client = [PubNub clientWithConfiguration:configuration];
5self.client.filterExpression = @"(senderID=='PubNub')";
Get filter expression
1NSLog(@"Filtering expression: %@", self.client.filterExpression);
Returns
Returns the current filter expression.
Warning
If filter expression is malformed, PNObjectEventListener won't receive any messages and presence events from service (only error status).