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:
+ (instancetype)configurationWithPublishKey:(NSString *)publishKey
subscribeKey:(NSString *)subscribeKey;
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. |
heartbeatNotificationOptions Type: PNHeartbeatNotificationOptions | Heartbeat notifications. Success , Failure (default), All , or None . |
stripMobilePayload Type: BOOL | If YES , remove push payload metadata (APNs/FCM) from received messages. |
subscribeMaximumIdleTime Type: NSTimeInterval | Max seconds to wait for events. Default: 310 . |
nonSubscribeRequestTimeout Type: NSTimeInterval | Timeout for non‑subscribe ops, in seconds. Default: 10 . |
presenceHeartbeatValue Type: NSInteger | Presence timeout (seconds). Defaults to 300 . Triggers timeout if no heartbeat. |
presenceHeartbeatInterval Type: NSInteger | Heartbeat interval (seconds). Typical: (presenceHeartbeatValue / 2) - 1 . Min 3 . |
keepTimeTokenOnListChange Type: BOOL | Keep previous timetoken on subscribe list change. Default: YES . |
catchUpOnSubscriptionRestore Type: BOOL | Catch up on missed events after restore. Default: YES . |
applicationExtensionSharedGroupIdentifier Type: NSString | Shared App Group ID for extensions (iOS 8.0+, macOS 10.10+). |
requestMessageCountThreshold Type: NSUInteger | Max messages per response before PNRequestMessageCountExceededCategory . |
maximumMessagesCacheSize Type: NSUInteger | De‑duplication cache size. Default: 100 . |
completeRequestsBeforeSuspension Type: BOOL | Finish in‑flight API calls before suspension. Default: YES . |
suppressLeaveEvents Type: BOOL | If YES , don’t send presence leave events on unsubscribe. |
origin Type: NSString | Custom origin (domain). Example: "ps.pndsn.com". |
requestRetry Type: PNRequestRetryConfiguration | Retry policy settings. See requestRetry . |
cryptoModule Type: [PNCryptoModule AESCBCCryptoModuleWithCipherKey: NSString randomInitializationVector: BOOL]; [PNCryptoModule legacyCryptoModuleWithCipherKey: NSString randomInitializationVector: BOOL]; | Encrypt/decrypt module. Takes cipherKey and useRandomInitializationVector . See cryptoModule. |
cipherKey Type: | 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. |
useRandomInitializationVector Type: | 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
+ (instancetype)configurationWithLinearDelay;
Example
configuration.requestRetry = [PNRequestRetryConfiguration configurationWithLinearDelay];
Create a linear retry policy with excluded endpoints
+ (instancetype)configurationWithLinearDelayExcludingEndpoints:(PNEndpoint)endpoints, ...;
Parameter | Description |
---|---|
endpoints Type: PNEndpoint | The endpoints to exclude. For a list of endpoints, inspect NS_ENUM(NSUInteger, PNEndpoint) in the PNStructures file. |
Example
configuration.requestRetry = [PNRequestRetryConfiguration configurationWithLinearDelayExcludingEndpoints:PNMessageSendEndpoint, 0];
Create a linear retry policy with excluded endpoints and custom parameters
+ (instancetype)configurationWithLinearDelay:(NSTimeInterval)delay
maximumRetry:(NSUInteger)maximumRetry
excludedEndpoints:(PNEndpoint)endpoints, ...;
Parameter | Description |
---|---|
delay Type: NSTimeInterval | Delay in seconds between failed requests. |
maximumRetry Type: NSUInteger | How many times to retry before throwing an error. |
excludedEndpoints Type: PNEndpoint | The endpoints to exclude. For a list of endpoints, inspect NS_ENUM(NSUInteger, PNEndpoint) in the PNStructures file. |
Example
/// example
configuration.requestRetry = [PNRequestRetryConfiguration configurationWithLinearDelay:3.f
maximumRetry:3
excludedEndpoints:PNMessageSendEndpoint, PNMessageStorageEndpoint, 0];
Create a default exponential retry policy
+ (instancetype)configurationWithExponentialDelay;
Example
configuration.requestRetry = [PNRequestRetryConfiguration configurationWithExponentialDelay];
Create an exponential retry policy with excluded endpoints
+ (instancetype)configurationWithExponentialDelayExcludingEndpoints:(PNEndpoint)endpoints, ...;
Parameter | Description |
---|---|
endpoints Type: PNEndpoint | The endpoints to exclude. For a list of endpoints, inspect NS_ENUM(NSUInteger, PNEndpoint) in the PNStructures file. |
Example
configuration.requestRetry = [PNRequestRetryConfiguration configurationWithExponentialDelayExcludingEndpoints:PNMessageSendEndpoint, 0];
Create an exponential retry policy with excluded endpoints and custom parameters
+ (instancetype)configurationWithExponentialDelay:(NSTimeInterval)minimumDelay
maximumDelay:(NSTimeInterval)maximumDelay
maximumRetry:(NSUInteger)maximumRetry
excludedEndpoints:(PNEndpoint)endpoints, ...;
Parameter | Description |
---|---|
minimumDelay Type: NSTimeInterval | Base delay in seconds used to calculate the next delay. |
maximumDelay Type: NSTimeInterval | Maximum allowed computed delay in seconds between retry attempts. |
maximumRetry Type: NSUInteger | How many times to retry before throwing an error. |
excludedEndpoints Type: 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.
// Basic configuration
PNConfiguration *config = [PNConfiguration configurationWithPublishKey:@"demo"
subscribeKey:@"demo"
userID:@"myUniqueUserID"];
// Create a PubNub client instance
PubNub *client = [PubNub clientWithConfiguration:config];
// Add listener for PubNub events
[client addListener:self];
// Subscribe to a test channel
PNSubscribeRequest *subscribeRequest = [PNSubscribeRequest requestWithChannels:@[@"test-channel"]
channelGroups:nil];
subscribeRequest.observePresence = YES;
show all 51 linesReturns
Returns a configured client configuration instance.
Other examples
Configure heartbeat notifications
PNConfiguration
PNConfiguration *config = [PNConfiguration configurationWithPublishKey:@"<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 = PNHeartbeatNotifyAll;
self.client = [PubNub clientWithConfiguration:config];
[self.client addListener:self];
Listener
- (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status {
if (status.operation == PNHeartbeatOperation) {
/**
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. */ }
}
}
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
pod init
platform :ios, '9.0'
target 'application-target-name' do
use_frameworks!
pod "PubNub", "~> 4"
end
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 install
via 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:
#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.
#import <PubNub/PubNub.h>
@interface AppDelegate () <PNObjectEventListener>
// Stores reference on PubNub client to make sure what it won't be released.
@property (nonatomic, strong) PubNub *client;
@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
+ (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
+ (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. |
callbackQueue Type: 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.
PNConfiguration *config = [PNConfiguration configurationWithPublishKey:@"demo"
subscribeKey:@"demo"
userID:@"myUserID"];
config.TLSEnabled = YES;
self.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.
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo"
subscribeKey:@"demo"
userID:@"myUserID"];
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:
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.
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@""
subscribeKey:@"demo"
userID:@"myUserID"];
self.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.
// Adding listener.
[pubnub addListener:self];
// Callbacks listed below.
- (void)client:(PubNub *)pubnub didReceiveMessage:(PNMessageResult *)message {
NSString *channel = message.data.channel; // Channel on which the message has been published
NSString *subscription = message.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
NSNumber *timetoken = message.data.timetoken; // Publish timetoken
id msg = message.data.message; // Message payload
NSString *publisher = message.data.publisher; // Message publisher
}
- (void)client:(PubNub *)pubnub didReceiveSignal:(PNSignalResult *)signal {
NSString *channel = message.data.channel; // Channel on which the signal has been published
show all 102 linesRemove listeners
[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.
- (void)client:(PubNub *)pubnub didReceiveStatus:(PNStatus *)status {
if (status.isError && status.willAutomaticallyRetry) {
// Stop automatic retry attempts.
[status cancelAutomaticRetry];
}
}
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)
@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.
// User authorized and we need to update used UUID
PNConfiguration *configuration = self.client.currentConfiguration;
configuration.userID = @"myUniqueUserID";
__weak __typeof(self) weakSelf = self;
[self.client copyWithConfiguration:configuration completion:^(PubNub *client) {
weakSelf.client = client;
}];
Other examples
Creating a function to subscribe a unique channel name
/**
Subscription process results arrive to listener which should adopt to
PNObjectEventListener protocol and registered using:
*/
[self.client addListener:self];
[self.client subscribeToChannels:@[[NSUUID UUID].UUIDString] withPresence:NO];
// Handle new message from one of channels on which client has been subscribed.
- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {
// Handle new message stored in message.data.message
if (![message.data.channel isEqualToString:message.data.subscription]) {
// Message has been received on channel group stored in message.data.subscription.
}
show all 77 linesCreating a unique auth_key for Access Manager on initialization
PNConfiguration *configuration = self.client.currentConfiguration;
configuration.authKey = [NSUUID UUID].UUIDString.lowercaseString;
__weak __typeof(self) weakSelf = self;
[self.client copyWithConfiguration:configuration completion:^(PubNub *client) {
// Store reference on new client with updated configuration.
weakSelf.client = client;
}];
Authentication key
Set and get the auth key.
Method(s)
Authentication key
@property (nonatomic, nullable, copy) NSString *authKey;
UserID
@property (nonatomic, copy, setter = setUserID:) NSString *userID;
Sample code
Set auth key
PNConfiguration *configuration = self.client.currentConfiguration;
configuration.authKey = @"my_new_authkey";
__weak __typeof(self) weakSelf = self;
[self.client copyWithConfiguration:configuration completion:^(PubNub *client) {
// Store reference on new client with updated configuration.
weakSelf.client = client;
}];
Get auth key
// Request current client configuration and pull out authorisation key from it.
NSString *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)
@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.
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo"
subscribeKey:@"demo"
userID:@"myUserID"];
self.client = [PubNub clientWithConfiguration:configuration];
self.client.filterExpression = @"(senderID=='PubNub')";
Get filter expression
NSLog(@"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).