Realtime iOS Apps: Getting Started with Swift and PubNub

swift pubnub sdk realtime ios apiThis tutorial will get you up and running quickly using the PubNub iOS SDK for building realtime functionality into iOS applications. Power chat, stream financial data, or even control connected devices, all from an iOS device.

Even better, we’re very excited to announce the release of a completely redesigned iOS SDK – Version 4.0! In designing this version 4.0, we rebuilt the entire code base and took advantage of new features from Apple that allowed us to massively simplify and streamline the SDK. We think you’ll find it elegant, simple, and powerful.

With that being said, let’s get started!

Creating A New Project

First, open Xcode and Go To: File -> New -> Project

Select a Application Type and press Next.

Enter your App Name for the Product Name, set the Language to Swift, and Devices to iPhone and click Next.

Choose a directory to save your project, and click Create.

Installing CocoaPods

If you have never installed a Pod before, a really good tutorial on how to get started can be found the CocoaPods official website.

Once you have CocoaPods installed go ahead and open the PodFile for YourProject by going into your project’s root directory and typing:

and paste the following into your pod file:

Make sure you grab the most recent pod versions in your project.

Now just go ahead and update then install the pod by typing:

Also, it is important that after installing our pods here on out we operate entirely in the Workspace part of our project.

Adding a Bridging-Header

The next thing we need to do to connect our Swift app to our pods is create an Objective-C bridging header. To do this you need to create a new File (File -> New -> File) of type Objective-C File. Call this whatever you like because we will end up deleting this file. Here I have just called it testHeader.

When you see “Would you like to configure an Objective-C bridging header?” select Yes. This is the file we really care about, so you can delete the .m file you just created.

Now it will add some new files to your project. Click on the File: YourProject-Bridging-Header.h. Underneath the commented code we need to add an #import to our project to use the PubNub iOS SDK. To do this we simply add the following lines into this file:

Basic Publish/Subscribe


Go into your AppDelegate.swift and add the following:

Lastly, add the following function beneath:

Thats it! Go ahead and run your project, and visit your PubNub Dev Console to check out what you’ve done. You should see “Swift + PubNub!” has been published, and if you try publishing from the Dev Console you’ll see the message is received in your Xcode console.

Try PubNub Today

Connect up to 100 devices for Free