PubNub Objective-C SDK 5.3.0

This page outlines the steps to follow to create a simple Hello, World application with PubNub. This covers the basics of integrating PubNub in your application: setting up a connection to PubNub, and sending and receiving messages.

  1. PubNub account
  2. Download the SDK
  3. Send messages

PubNub account

Sign in or create an account to create an app on the Admin Portal and get the keys to use in your application.

When you create a new app, the first set of keys is generated automatically, but a single app can have as many keysets as you like. We recommend that you create separate keysets for production and test environments.

Download the SDK

Download the SDK from any of the following sources:

Use CocoaPods

To integrate PubNub into your project using CocoaPods

  1. Install the latest cocoapods gem by running the gem install cocoapods command. If you already have this gem, make sure to update to the latest version by running the gem update cocoapods command.

  2. Create a new Xcode project and create a Podfile in the root folder of the project:

    pod init
    platform :ios, '9.0'

    target 'application-target-name' do
    use_frameworks!

    pod "PubNub", "~> 4"
    end

    If you want to include additional pods or add other targets, add their entries to this Podfile as well, refer to the CocoaPods documentation for more information on Podfile configuration.

  3. Install your pods by running the pod install command from the directory which contains your Podfile. After installing your Pods, you should work with the CocoaPods-generated workspace and not the original project file.

  4. Import the PubNub headers in the classes where you want to use PubNub:

    #import <PubNub/PubNub.h>

Use Carthage

To build PubNub as a standalone bundle using Carthage and integrate it into your project:

  1. Install the latest release of Carthage and either create a new file or open an existing Cartfile.

  2. Add a new line in the Cartfile to build the PubNub framework bundle:

    github "pubnub/objective-c" ~> 4
  3. Update and rebuild your project's dependencies.

    The update command ensures that the latest PubNub client is used to build the framework. You can also use the faster build command if you have already built the framework before.

    carthage update --no-use-binaries

    The preceding command builds the framework for all configured platforms. You can use the following command to specify the platform:

    carthage update --platform ios --no-use-binaries

    Available platforms include mac, tvos, and watchos.

  4. Navigate to Carthage/Build and enter the directory which represents your target platform, for example: iOS.

  5. Drag and drop the PubNub.framework bundle from the Products directory to your application.

  6. Mark the Copy items if needed checkbox and click Finish.

  7. Open your project's General tab, scroll to Embedded Binaries, click +, and select the PubNub.framework file.

  8. At this point, you should have the framework added to your application project. Import the PubNub headers in the classes where you want to use PubNub:

    #import <PubNub/PubNub.h>

Get the source code

https://github.com/pubnub/objective-c

View the supported platforms here.

Configure PubNub

You will use the workspace you generated with CocoaPods in this procedure.

  1. In Xcode, open your workspace and add the following content to the AppDelegate class.

    @interface AppDelegate () <PNEventsListener>

    // Stores reference on PubNub client to make sure what it won't be released.
    @property (nonatomic, strong) PubNub *client;

    @end
  2. Below what you added in step 1, add the following code.

    This is the minimum configuration you need to send and receive messages with PubNub.

    Make sure to replace myPublishKey and mySubscribeKey with your app's publish and subscribe keys from the Admin Portal.

    // Initialize and configure PubNub client instance
    PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey: @"myPublishKey" subscribeKey:@"mySubscribeKey"];
    configuration.uuid = @"myUniqueUUID";

    self.client = [PubNub clientWithConfiguration:configuration];

For more information, refer to the Configuration section of the SDK documentation.

Add event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

Copy the following code to configure your app such that when it receives an event of type PNConnectedCategory, it calls the publish function. Additionally, the code below prints out the content of every received message.

[self.client addListener:self];

- (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[@"msg"],
message.data.channel, message.data.timetoken);
}

show all 72 lines

For more information, refer to the Listeners section of the SDK documentation.

Publish and subscribe

To receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone subscribed to that channel.

In this app, publishing a message is triggered when the status listener you created in the previous step receives the PNConnectedCategory event. The publish method uses the targetChannel variable that you can see in the code below.

To subscribe, you send a subscribe call:

[self.client subscribeToChannels: @[@"hello-world-channel"] withPresence:YES];

For more information, refer to the Publish and Subscribe section of the SDK documentation, and to Publishing a Message.

Putting it all together

Your AppDelegate class should now look similar to the following snippet. Note that it contains code for different platforms.

<!-- MACOS -->

@interface AppDelegate () <PNEventsListener>

// Stores reference on PubNub client to make sure what it won't be released.
@property (nonatomic, strong) PubNub *client;

@end

@implementation PNAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Initialize and configure PubNub client instance
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey:@"myPublishKey"
subscribeKey:@"mySubscribeKey"];
show all 186 lines

Now, run your app to see if you did everything correctly.

You should see output similar to the following:

Received message: Hello on channel hello-world-channel at 15844898827972406

Congratulations! You've just subscribed to a channel and sent your first message.

Walkthrough

Instead of focusing on the order in which you wrote the code, let's focus on the order in which it runs. The app you just created does a few things:

  • configures a PubNub connection
  • adds the status and message event listeners
  • subscribes to a channel
  • publishes a message

Configuring PubNub

The following code is the minimum configuration you need to send and receive messages with PubNub. For more information, refer to the Configuration section of the SDK documentation.

// Initialize and configure PubNub client instance
PNConfiguration *configuration = [PNConfiguration configurationWithPublishKey: @"myPublishKey" subscribeKey: @"mySubscribeKey"];
configuration.uuid = @"myUniqueUUID";

self.client = [PubNub clientWithConfiguration:configuration];

Add event listeners

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event.

You added two listeners to the app: status and message. Status listens for status events and when it receives an event of type PNConnectedCategory, it publishes the message. The other listener, message, listens for incoming messages on a particular channel. When it receives a message, the app simply prints the received message. This is why you see "Received message: Hello on channel hello-world-channel at 15844898827972406" displayed in the console.

[self.client addListener:self];

- (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[@"msg"],
message.data.channel, message.data.timetoken);
}

show all 72 lines

For more information, refer to the Listeners section of the SDK documentation.

Publishing and subscribing

PubNub uses the Publish/Subscribe model for real-time communication. This model involves two essential parts:

  • Channels are transient paths over which your data is transmitted
  • Messages contain the data you want to transmit to one or more recipients

When you want to receive messages sent to a particular channel, you subscribe to it. When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel. In this example, you subscribe to a channel named myChannel.

A message can be any type of JSON-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB. PubNub will, in most cases, deliver your message to its intended recipients in fewer than 100 ms regardless of their location. You can also share files up to 5MB.

When your app successfully connects to a channel, it calls the publish method, which effectively sends the "Hello" message. This behavior is configured in the status listener.

[self.client publish: @{ @"msg": @"Hello" } toChannel:targetChannel
withCompletion:^(PNPublishStatus *publishStatus) {
}];

You can subscribe to more than one channel with a single subscribe call but in this example, you subscribe to a single channel:

[self.client subscribeToChannels: @[@"hello-world-channel"] withPresence:YES];

For more information, refer to the Publish and Subscribe section of the SDK documentation, and to Publishing a Message.

Next steps

You have just learned how to use the Objective-C SDK to send and receive messages using PubNub. Next, take a look at the SDK's reference documentation documentation, which covers PubNub API in more detail.

Last updated on