Configuration API for PubNub Objective-C SDK
Objective-C complete API reference for building real-time applications on PubNub, including basic usage and sample code.
Native Docs Links
Configuration
Description
PNConfiguration
instance is storage for user-provided information which describe further PubNub client behavior. Configuration instance contain additional set of properties which allow to perform precise PubNub client configuration.
Method(s)
To create configuration
instance you can use the following function in the Objective-C SDK:
+ (instancetype)configurationWithPublishKey:(NSString *)publishKey subscribeKey:(NSString *)subscribeKey;
Parameter | Type | Required | Description |
---|---|---|---|
publishKey | NSString | Yes | Key which allow client to use data push API. |
subscribeKey | NSString | Yes | Key which allow client to subscribe on live feeds pushed from PubNub service. |
heartbeatNotificationOptions | PNHeartbeatNotificationOptions | No | 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 | No | Stores whether client should strip out received messages (real-time and history) from data which has been appended by client (like mobile payload for push notifications). |
cipherKey | NSString | No | 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 | NSTimeInterval | No | Maximum number of seconds which client should wait for events from live feed. Default 310 . |
nonSubscribeRequestTimeout | NSTimeInterval | No | 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 | NSInteger | No | Number of seconds which is used by server to track whether client still subscribed on remote data objects live feed or not. |
presenceHeartbeatInterval | NSInteger | No | Number of seconds which is used by client to issue heartbeat requests to PubNub service. |
keepTimeTokenOnListChange | BOOL | No | Whether client should keep previous timetoken when subscribe on new set of remote data objects live feeds. Default YES . |
catchUpOnSubscriptionRestore | BOOL | No | Whether client should try to catch up for events which occurred on previously subscribed remote data objects feed while client was off-line. Default YES . |
applicationExtensionSharedGroupIdentifier | NSString | No | 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 | NSUInteger | No | Number of maximum expected messages from PubNub service in single response. |
maximumMessagesCacheSize | NSUInteger | No | Messages de-duplication cache size Default 100 . |
completeRequestsBeforeSuspension | BOOL | No | Whether client should try complete all API call which is done before application will be completely suspended. Default YES . |
suppressLeaveEvents | BOOL | No | If YES , the client shouldn't send presence leave events during the unsubscribe process. |
origin | NSString | No | If a custom domain is required, SDK accepts it here. |
useRandomInitializationVector | BOOL | No | When 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.
Basic Usage
Note
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.
PNConfiguration *config = [PNConfiguration configurationWithPublishKey:@"demo"
subscribeKey:@"demo"];
config.uuid = @"myUniqueUUID";
self.client = [PubNub clientWithConfiguration:config];
[self.client addListener:self];
Returns
Configured and ready to use client configuration instance.
Other Examples
Configure heartbeat notifications
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];
- (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
To include PubNub SDK in your project you need to use CocoaPods.
Install CocoaPods gem by following the procedure defined under How to Get It To add the PubNub SDK to your project with CocoaPods, there are four basic tasks to complete which are covered below:
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 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.
- 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!
To be able to use PubNub SDK within your application code you need to import it. Import PubNub SDK headers in implementation files for classes where you need to use it using this import statement:
#import <PubNub/PubNub.h>
Complete application delegate configuration
Add the PNObjectEventListener protocol to AppDelegate in implementation file to anonymous category:
Note
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.
#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
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 Objective-C SDK:
+ (instancetype)clientWithConfiguration:(PNConfiguration *)configuration;
Parameter Type Required Description configuration
PNConfiguration Yes Reference on instance which store all user-provided information about how client should operate and handle events. + (instancetype)clientWithConfiguration:(PNConfiguration *)configuration callbackQueue:(dispatch_queue_t)callbackQueue;
Parameter Type Required Description configuration
PNConfiguration Yes Reference on instance which store all user-provided information about how client should operate and handle events. callbackQueue
dispatch_queue_t No Reference on queue which should be used by client for completion block and delegate calls.
Basic Usage
Initialize the PubNub client API:
Note
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.
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo"
subscribeKey:@"demo"];
configuration.TLSEnabled = YES;
configuration.uuid = @"myUniqueUUID";
self.client = [PubNub clientWithConfiguration:configuration];
Returns
It returns the PubNub instance for invoking PubNub APIs like publish
, subscribeToChannels
, historyForChannel
, hereNowForChannel
, etc.
Other Examples
-
Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set theUUID
, you won't be able to connect to PubNub.PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo" subscribeKey:@"demo"]; configuration.uuid = @"myUniqueUUID"; 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
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set theUUID
, you won't be able to connect to PubNub.PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"" subscribeKey:@"demo"]; self.client = [PubNub clientWithConfiguration:configuration];
-
Set a custom
UUID
to identify your users.Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set theUUID
, you won't be able to connect to PubNub.PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"myPublishKey" subscribeKey:@"mySubscribeKey"]; configuration.uuid = @"myUniqueUUID"; self.client = [PubNub clientWithConfiguration:configuration];
Event Listeners
Description
You can be notified of connectivity status, message and presence notifications via the listeners.
Listeners should be added before calling the method.
Adding Listeners
Listener's class should conform to PNEventsListener
protocol to have access to available 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
NSString *subscription = message.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
NSNumber *timetoken = message.data.timetoken; // Signal timetoken
id msg = message.data.message; // Signal payload
NSString *publisher = message.data.publisher; // Signal publisher
}
- (void)client:(PubNub *)pubnub didReceiveMessageAction:(PNMessageActionResult *)action {
NSString *channel = action.data.channel; // Channel on which the message has been published
NSString *subscription = action.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
NSString *event = action.data.event; // Can be: added or removed
NSString *type = action.data.action.type; // Message action type
NSString *value = action.data.action.value; // Message action value
NSNumber *messageTimetoken = action.data.action.messageTimetoken; // Timetoken of the original message
NSNumber *actionTimetoken = action.data.action.actionTimetoken; // Timetoken of the message action
NSString *uuid = action.data.action.uuid; // UUID of user which added / removed message action
}
- (void)client:(PubNub *)pubnub didReceivePresenceEvent:(PNPresenceEventResult *)event {
NSString *channel = message.data.channel; // Channel on which presence changes
NSString *subscription = message.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
NSString *presenceEvent = event.data.presenceEvent; // Can be: join, leave, state-change, timeout or interval
NSNumber *occupancy = event.data.presence.occupancy; // Number of users subscribed to the channel (not available for state-change event)
NSNumber *timetoken = event.data.presence.timetoken; // Presence change timetoken
NSString *uuid = event.data.presence.uuid; // UUID of user for which presence change happened
// Only for 'state-change' event
NSDictionary *state = event.data.presence.state; // User state (only for state-change event)
// Only for 'interval' event
NSArray<NSString *> *join = event.data.presence.join; // UUID of users which recently joined channel
NSArray<NSString *> *leave = event.data.presence.leave; // UUID of users which recently leaved channel
NSArray<NSString *> *timeout = event.data.presence.timeout; // UUID of users which recently timed out on channel
}
- (void)client:(PubNub *)pubnub didReceiveObjectEvent:(PNObjectEventResult *)event {
NSString *channel = event.data.channel; // Channel to which the event belongs
NSString *subscription = event.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
NSString *event = event.data.event; // Can be: set or delete
NSString *type = event.data.type; // Entity type: channel, uuid or membership
NSNumber *timestamp = event.data.timestamp; // Event timestamp
PNChannelMetadata *channelMetadata = event.data.channelMetadata; // Updated channel metadata (only for channel entity type)
PNUUIDMetadata *uuidMetadata = event.data.uuidMetadata; // Updated channel metadata (only for uuid entity type)
PNMembership *membership = event.data.membership; // Updated channel metadata (only for membership entity type)
}
- (void)client:(PubNub *)pubnub didReceiveFileEvent:(PNFileEventResult *)event {
NSString *channel = event.data.channel; // Channel to which file has been uploaded
NSString *subscription = event.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
id message = event.data.message; // Message added for uploaded file
NSString *publisher = event.data.publisher; // UUID of file uploader
NSURL *fileDownloadURL = event.data.file.downloadURL; // URL which can be used to download file
NSString *fileIdentifier = event.data.file.identifier; // Unique file identifier
NSString *fileName = event.data.file.name; // Name with which file has been stored remotely
}
- (void)client:(PubNub *)pubnub didReceiveStatus:(PNStatus *)status {
PNStatusCategory category = status.category; // One of PNStatusCategory fields to identify status of operation processing
PNOperationType operation = status.operation; // One of PNOperationType fields to identify for which operation status received
BOOL isError = status.isError; // Whether any kind of error happened.
NSInteger statusCode = status.statusCode; // Related request processing status code
BOOL isTLSEnabled = status.isTLSEnabled; // Whether secured connection enabled
NSString *uuid = status.uuid; // UUID which configured for passed client
NSString *authKey = status.authKey; // Auth key configured for passed client
NSString *origin = status.origin; // Origin against which request has been sent
NSURLRequest *clientRequest = status.clientRequest; // Request which has been used to send last request (may be nil)
BOOL willAutomaticallyRetry = status.willAutomaticallyRetry; // Whether client will try to perform automatic retry
// Following information available when operation == PNSubscribeOperation, because status is PNSubscribeStatus instance in this case
PNSubscribeStatus *subscribeStatus = (PNSubscribeStatus *)status;
NSNumber *currentTimetoken = subscribeStatus.currentTimetoken; // Timetoken which has been used for current subscribe request
NSNumber *lastTimeToken = subscribeStatus.lastTimeToken; // Timetoken which has been used for previous subscribe request
NSArray<NSString *> *subscribedChannels = subscribeStatus.subscribedChannels; // List of channels on which client currently subscribed
NSArray<NSString *> *subscribedChannelGroups = subscribeStatus.subscribedChannelGroups; // List of channel groups on which client currently subscribed
NSString *channel = subscribeStatus.data.channel; // Name of channel for which status has been received
NSString *subscription = subscribeStatus.data.subscription; // Wild-card channel or channel on which PubNub client actually subscribed
NSNumber *timetoken = subscribeStatus.data.timetoken; // Timetoken at which event arrived
NSDictionary *userMetadata = subscribeStatus.data.userMetadata; // Metadata / envelope which has been passed along with event
// Following information available when isError == YES, because status is PNErrorStatus instance in this case
PNErrorStatus *errorStatus = (PNErrorStatus *)status;
id associatedObject = errorStatus.associatedObject; // Data which may contain related information (not decrypted message for example)
NSArray<NSString *> *erroredChannels = errorStatus.errorData.channels; // List of channels for which error reported (mostly because of PAM)
NSArray<NSString *> *erroredChannelGroups = errorStatus.errorData.channelGroups; // List of channel groups for which error reported (mostly because of PAM)
NSString *errorInformation = errorStatus.errorData.information; // Stringified information about error
id errorData = errorStatus.errorData.data; // Additional error information from PubNub service
}
Removing Listeners
[pubnub removeListener:self]
Handling Disconnects
SDK performs automated re-connections and call status handler to report back. This will happen forever, but user may decide to stop it.
- (void)client:(PubNub *)pubnub didReceiveStatus:(PNStatus *)status {
if (status.isError && status.willAutomaticallyRetry) {
// Stop automatic retry attempts.
[status cancelAutomaticRetry];
}
}
Listener status events
Category | Description |
---|---|
PNAcknowledgmentCategory | Reported operation request acknowledgment status. |
PNAccessDeniedCategory | PAM permission failure. |
PNTimeoutCategory | Server didn't respond in time for reported operation request. |
PNNetworkIssuesCategory | No connection to Internet. |
PNRequestMessageCountExceededCategory | The SDK announces this error if requestMessageCountThreshold is set, and the number of messages received from PubNub (in-memory cache messages) exceeds the threshold. |
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 | The SDK unexpectedly lost ability to receive live updated from PubNub. |
PNRequestURITooLongCategory | Reported operation request URI too long (too many channels / channel groups). |
PNMalformedFilterExpressionCategory | The SDK has been configured with malformed filtering expression. |
PNMalformedResponseCategory | The SDK received unexpected PubNub service response. |
PNDecryptionErrorCategory | The SDK unable to decrypt received message using configured cipherKey . |
PNTLSConnectionFailedCategory | The SDK unable to establish secured connection. |
PNTLSUntrustedCertificateCategory | The SDK unable to check certificates trust chain. |
UUID
Description
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 Objective-C SDK:
@property (nonatomic, copy, setter = setUUID:) NSString *uuid;
Basic Usage
Note
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.
// User authorized and we need to update used UUID
PNConfiguration *configuration = self.client.currentConfiguration;
configuration.uuid = @"myUniqueUUID";
__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. } else { // Message has been received on channel stored in message.data.channel. } NSLog(@"Received message: %@ on channel %@ at %@", message.data.message, message.data.channel, message.data.timetoken); } // Handle subscription status change. - (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status { if (status.operation == PNSubscribeOperation) { // Check whether received information about successful subscription or restore. if (status.category == PNConnectedCategory || status.category == PNReconnectedCategory) { // Status object for those categories can be casted to `PNSubscribeStatus` for use below. PNSubscribeStatus *subscribeStatus = (PNSubscribeStatus *)status; 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 { PNErrorStatus *errorStatus = (PNErrorStatus *)status; if (errorStatus.category == PNAccessDeniedCategory) { /** This means that PAM 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
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set theUUID
, you won't be able to connect to PubNub.PNConfiguration *configuration = self.client.currentConfiguration; configuration.uuid = @"myUniqueUUID"; __weak __typeof(self) weakSelf = self; [self.client copyWithConfiguration:configuration completion:^(PubNub *client) { // Store reference on new client with updated configuration. weakSelf.client = client; }];
Creating a unique auth_key for PAM 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
Description
Setter and getter for users auth key.
Method(s)
@property (nonatomic, nullable, copy) NSString *authKey;
@property (nonatomic, copy, setter = setUUID:) NSString *uuid;
Basic Usage
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;
}];
// 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-onRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-
Description
Stream filtering allows a subscriber to apply a filter to only receive messages that satisfy the conditions of the filter. The message filter is set by the subscribing client(s) but it is applied on the server side thus preventing unwanted messages (those that do not meet the conditions of the filter) from reaching the subscriber.
To set/get filters you can use the following property. To learn more about filtering, refer to the Publish Messages documentation.
Method(s)
@property (nonatomic, nullable, copy) NSString *filterExpression;
Basic Usage
Note
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.
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo"
subscribeKey:@"demo"];
self.client = [PubNub clientWithConfiguration:configuration];
self.client.filterExpression = @"(senderID=='PubNub')";
NSLog(@"Filtering expression: %@", self.client.filterExpression);
Returns
Get Filter Expression
returns the Current filtering expression
.
Set Filter Expression:
Warning
If filter expression is malformed, PNObjectEventListener
won't receive any messages and presence events from service (only error status).