Cocoa Objective-C API & SDK Docs 6.1.0

Unsupported SDK

PubNub no longer supports this SDK, but you are welcome to contribute.

Get code: CocoaPods

CocoaPods is a dependency manager and this is by far the easiest and quickest way to get started with PubNub Cocoa SDK! (If you don't have pods installed yet you can check CocoaPods installation section for installation guide).

Be sure you are running CocoaPods 1.0.0 or above! You can install the latest cocoapods gem:

1gem install cocoapods

If you've already installed you can upgrade to the latest CocoaPods gem using:

1gem update cocoapods

Get code: Git

Add the PubNub Cocoa SDK folder to your project.

Get code: framework

The PubNub framework project allows you to build standalone framework bundles which can be copied right into your application.

To build the framework as a standalone bundle and integrate into project, perform the following:

  1. Clone the PubNub master repository

    1git clone git@github.com:pubnub/objective-c.git
  2. Navigate to root of the cloned repository

  3. Run the CocoaPods pod install command to pull out all required dependencies

    1`pod install`
  4. Open the PubNub.xcworkspace from the PubNub repository in Xcode.

  5. Select the Framework or Universal Framework target for target platform and hit Cmd+B to build the selected type of framework. Select Framework target

  6. Navigate to the Framework directory and find the Products directory. Navigate to Framework bundle

  7. Drag&Drop PubNub.framework bundle from the Products directory to your application. Drag & drop Framework bundle

  8. Select the Copy items if needed checkbox and click Finish. Copy Framework bundle

  9. Open your project's General tab and scroll to Embedded Binaries. Open embedded binaries group Objective C

  10. Click on + and select PubNub.framework file. Add Framework bundle to embedded binaries group

PubNub-Universal

If the PubNub target has been used, then the framework will be generated only for the selected platform (device or simulator.) If you try to use the framework to compile for another platform, it will crash during run-time. Using the PubNub-Universal build target (which can be used on both device and simulator) will help mitigate any sort of crash scenarios during development.

Now that these steps are complete, let's learn more about how to use the framework in your app.

Using the framework with your app

At this point, you should have the framework added to your application project, we'll need to make your project aware of the PubNub framework.

You need to import the PubNub headers in classes where it will be used.

1#import <PubNub/PubNub.h>

Get code: Carthage

To build the framework as a standalone bundle and integrate into project, perform the following:

  1. Install latest Carthage (if required).

  2. Create a Cartfile (any location can be used) or use existing file.

    1touch Cartfile
  3. Add next line into a Cartfile which will allow to build framework bundles

    1github "pubnub/objective-c" ~> 4.1
  4. Update and rebuild the project's dependencies (update command ensure what latest PubNub client code will be used to build framework). build can be used if frameworks has been built before and it will be much faster because git clone will be skipped.

    1carthage update

    Command above will build framework for all configured platforms, but if only one required it can be called like this

    1carthage update --platform ios

    Instead of ios can be used: mac, tvos or watchos

  5. Navigate to the Carthage directory and find the Build directory.

  6. Navigate to directory which represent your target platform. For example: iOS Navigate to built framework bundle for Carthage

  7. Drag&Drop PubNub.framework bundle from the Products directory to your application. Drag &amp; drop Framework bundle for Carthage

  8. Select the Copy items if needed checkbox and click Finish. Copy Framework bundle for Carthage

  9. Open your project's General tab and scroll to Embedded Binaries. Open embedded binaries group Objective C for Carthage

  10. Click on + and select PubNub.framework file. Add Framework bundle to embedded binaries group for Carthage

Using the framework with your app

At this point, you should have the framework added to your application project, we'll need to make your project aware of the PubNub framework.

You need to import the PubNub headers in classes where it will be used.

1#import <PubNub/PubNub.h>

Get code: source

Hello World

Include PubNub SDK in your project you need to use CocoaPods

Install CocoaPods gem by following the procedure defined above. To add the PubNub SDK to your project with CocoaPods, there are four basic tasks to complete which are covered below:

  1. Create new Xcode project.

  2. Create Podfile in new Xcode project root folder

    1touch Podfile
  3. The PubNub client can be added as module (only with a deployment target of OS X 10.9 and above):

    1source 'https://github.com/CocoaPods/Specs.git'
    2platform :osx, "10.9"
    3use_frameworks!
    4
    5target 'application-target-name' do
    6 pod "PubNub", "~> 4.1"
    7end

    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.

  4. Install your pods by running pod install via the command line from the directory that contains your Podfile.

Work within the workspace

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:

1#import <PubNub/PubNub.h>

Complete application delegate configuration

Add the PNObjectEventListener protocol to AppDelegate in implementation file to anonymous category:

Required UUID

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.

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
Required UUID

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.

1// Initialize and configure PubNub client instance
2PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo" subscribeKey:@"demo"];
3configuration.uuid = @"myUniqueUUID";
4
5self.client = [PubNub clientWithConfiguration:configuration];
6[self.client addListener:self];
7
8// Subscribe to demo channel with presence observation
9[self.client subscribeToChannels: @[@"my_channel"] withPresence:YES];
10
11// Handle new message from one of channels on which client has been subscribed.
12- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {
13
14 // Handle new message stored in message.data.message
15 if (![message.data.channel isEqualToString:message.data.subscription]) {
show all 128 lines

Copy and paste examples

In addition to the Hello World sample code, we also provide some copy and paste snippets of common API functions:

Init

Instantiate a new Pubnub instance. Only the subscribeKey is mandatory. Also include publishKey if you intend to publish from this instance, and the secretKey if you wish to perform Access Manager administrative operations from this Cocoa instance.

Secure your secretKey

It is not a best practice to include the secret key in client-side code for security reasons.

When you init with secretKey, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.

Required UUID

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.

1PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"demo"
2 subscribeKey:@"demo"];
3configuration.uuid = @"myUniqueUUID";
4self.client = [PubNub clientWithConfiguration:configuration];
PubNub instance as property

PubNub instance should be placed as a property in a long-life object (otherwise PubNub instance will be automatically removed as autoreleased object).

1@property (nonatomic, strong) PubNub *client;

Listeners

Add listeners

Listener's class should conform to PNEventsListener protocol to have access to available 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 = signal.data.channel; // Channel on which the signal has been published
show all 102 lines

Remove listeners

1[pubnub removeListener:self]

Listener status events

CategoryDescription
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 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.

Subscribe

Subscribe (listen on) a channel (it's async!):

1/**
2 Subscription results arrive to a listener which should implement the
3 PNObjectEventListener protocol and be registered as follows:
4 */
5[self.client addListener:self];
6[self.client subscribeToChannels: @[@"my_channel1", @"my_channel2"] withPresence:NO];
7
8// Handle a new message from a subscribed channel
9- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {
10 // Reference to the channel group containing the chat the message was sent to
11 NSString *subscription = message.data.subscription;
12 NSLog(@"%@ sent message to '%@' at %@: %@", message.data.publisher, message.data.channel,
13 message.data.timetoken, message.data.message);
14}
15
show all 97 lines
Event listeners

The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.

Publish

Publish a message to a channel:

1[self.client publish: @{@"Dictionary": @[@"with",@"array",@"as", @"value"]}
2 toChannel: @"pubnub" withCompletion:^(PNPublishStatus *status) {
3
4 if (!status.isError) {
5
6 // Message successfully published to specified channel.
7 }
8 else {
9
10 /**
11 Handle message publish error. Check 'category' property to find
12 out possible reason because of which request did fail.
13 Review 'errorData' property (which has PNErrorData data type) of status
14 object to get additional information about issue.
15
show all 19 lines

Here now

Get occupancy of who's here now on the channel by UUID:

Requires Presence

This method requires that the Presence add-on is enabled for your key in the Admin Portal.

1// With PNHereNowUUID client will pull out list of unique identifiers and occupancy information.
2[self.client hereNowForChannel: @"my_channel" withVerbosity:PNHereNowUUID
3 completion:^(PNPresenceChannelHereNowResult *result,
4 PNErrorStatus *status) {
5
6 // Check whether request successfully completed or not.
7 if (!status) {
8
9 /**
10 Handle downloaded presence information using:
11 result.data.uuids - list of uuids.
12 result.data.occupancy - total number of active subscribers.
13 */
14 }
15 else {
show all 26 lines

Presence

Subscribe to real-time Presence events, such as join, leave, and timeout, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel:

Requires Presence

This method requires that the Presence add-on is enabled for your key in the Admin Portal.

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 subscribeToPresenceChannels:@[@"my_channel"]];
7
8// New presence event handling.
9- (void)client:(PubNub *)client didReceivePresenceEvent:(PNPresenceEventResult *)event {
10
11 if (![event.data.channel isEqualToString:event.data.subscription]) {
12
13 // Presence event has been received on channel group stored in event.data.subscription.
14 }
15 else {
show all 31 lines
Event listeners

The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.

History

Retrieve published messages from archival storage:

Requires Message Persistence

This method requires that Message Persistence is enabled for your key in the Admin Portal.

1[self.client historyForChannel: @"my_channel" start:nil end:nil limit:100
2 withCompletion:^(PNHistoryResult *result, PNErrorStatus *status) {
3
4 if (!status) {
5
6 /**
7 Handle downloaded history using:
8 result.data.start - oldest message time stamp in response
9 result.data.end - newest message time stamp in response
10 result.data.messages - list of messages
11 */
12 }
13 else {
14
15 /**
show all 24 lines

Unsubscribe

Stop subscribing (listening) to a channel.

1/**
2 Unsubscription process results arrive to listener which should adopt to
3 PNObjectEventListener protocol and registered using:
4 */
5[self.client addListener:self];
6[self.client unsubscribeFromChannels: @[@"my_channel1", @"my_channel2"] withPresence:NO];
7
8// Handle subscription status change.
9- (void)client:(PubNub *)client didReceiveStatus:(PNStatus *)status {
10
11 if (status.operation == PNUnsubscribeOperation && status.category == PNDisconnectedCategory) {
12
13 /**
14 This is the expected category for an unsubscribe. This means there was no error in
15 unsubscribing from everything.
show all 18 lines
Event listeners

The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.

Last updated on