PubNub Swift SDK 6.0.3

Chat use-case

You can also build a chat app using ready-made building blocks that not only handle the back-end communication, but also provide the UI for your chat apps. For further information, visit documentation for PubNub Chat Components for iOS.

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 Swift Package Manager

To integrate PubNub into your project using the Swift Package Manager specify PubNub in the dependencies list of your Package.swift file:

dependencies: [
.package(url: "https://github.com/pubnub/swift.git", from: "6.0.3")
]

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. Add PubNub to your Podfile:

    pod 'PubNubSwift', '~> 6.0.3'

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/swift" ~> 6.0.3
  3. Update and rebuild your project's dependencies.

Get the source code

To integrate PubNub into your Xcode project using Embedded Framework do the following:

  1. In your top-level project directory add PubNub as a submodule:

    git submodule add https://github.com/pubnub/swift.git
  2. Open your app's Xcode project.

  3. In Finder, locate the PubNub.xcodeproj Xcode project inside the submodule directory, and drag it onto your app's project in the Project Navigator.

    This nests a reference to the framework project in the app project.

  4. Select your applications's project in the Project Navigator (blue project icon), navigate to the target configuration window, and select the application target under the "Targets" heading in the sidebar.

  5. Select your application project in the Project Navigator, and then select your application's Target under the TARGETS panel.

  6. Select the General tab in the top middle of the window, and then click + inside the EMBEDDED BINARIES section.

  7. Select PubNub.framework nested inside the top-most PubNub.xcodeproj/Products/ directory.

For more information, refer to Apple's guide on Adding Package Dependencies to Your App.

Configure PubNub

You will use the workspace you generated with Swift Package Manager in this procedure.

  1. Create a new Xcode project as a Single View App, using a Storyboard user interface.

  2. Navigate to File > Swift Packages > Add Package Dependency.

  3. Search for PubNub and select the swift package owned by pubnub, and click Next.

  4. Use the Up to Next Major Version rule spanning from 3.0.0 < 4.0.0, and click Next.

  5. Import the module named PubNub inside your AppDelegate:

    import UIKit
    import PubNub // <- Here is our PubNub module import.
  6. Create a PubNub object and pass it to your root view controller.

    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 PubNub Dashboard.

    import UIKit
    import PubNub

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {

    var pubnub: PubNub!
    var window: UIWindow?

    func application(_ application: UIApplication,
    willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
    PubNub.log.levels = [.all]
    PubNub.log.writers = [ConsoleLogWriter(), FileLogWriter()]

    var config = PubNubConfiguration(publishKey: "myPublishKey", subscribeKey: "mySubscribeKey", userId: "myUniqueUserId")
    show all 40 lines

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

  7. If using multiple Scenes, use the SceneDelegate to pass your PubNub instance to your view controllers:

    import UIKit
    import PubNub

    @available(iOS 13.0, *)
    class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?
    var pubnub: PubNub?

    func scene(
    _ scene: UIScene,
    willConnectTo session: UISceneSession,
    options connectionOptions: UIScene.ConnectionOptions
    ) {
    guard let windowScence = scene as? UIWindowScene,
    show all 29 lines

Add listeners, subscribe, and publish

Listeners help your app react to events and messages. You can implement custom app logic to respond to each type of message or event received. 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 successfully connects to a channel.

To subscribe, you send a subscribe() call. It is best to define the message before you introduce the listeners and send the subscribe call, so make sure to place the relevant code in the appropriate places.

Copy the code below to configure your app such that when it successfully connects to a channel, it calls the publish() function. The following code also subscribes to the channel awesomeChannel and prints out the message when it is received.

Set up your root ViewController:

import UIKit
import PubNub

class ViewController: UIViewController {

var pubnub: PubNub!
let channels = ["awesomeChannel"]
let listener = SubscriptionListener(queue: .main)

override func viewDidLoad() {
super.viewDidLoad()

listener.didReceiveMessage = { message in
print("[Message]: \(message)")
}
show all 33 lines

For more information, refer to the Listeners, Publish and Subscribe, and Message Publish sections of the documentation.

Now, run your app to see if you did everything correctly. You should see "Hello world" printed in the console.

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.

var config = PubNubConfiguration(publishKey: "myPublishKey", subscribeKey: "mySubscribeKey",   userId: "myUniqueUserId")
pubnub = PubNub(configuration: config)

Adding 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: message and status. The message listener 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 "Hello world" displayed in the console.

The status listener triggers the publishing of the "Hello world" message.

listener.didReceiveMessage = { message in
print("[Message]: \(message)")
}
listener.didReceiveStatus = { status in
switch status {
case .success(let connection):
if connection == .connected {
// publish message
}
case .failure(let error):
print("Status Error: \(error.localizedDescription)")
}
}

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

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 sends the "Hello world" message.

listener.didReceiveStatus = { status in
switch status {
case .success(let connection):
if connection == .connected {
self.pubnub.publish(channel: self.channels[0], message: "Hello, PubNub Swift!") { result in
print(result.map { "Publish Response at \($0.timetokenDate)" })
}
}
case .failure(let error):
print("Status Error: \(error.localizedDescription)")
}
}

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

let channels = ["awesomeChannel"]

pubnub.subscribe(to: channels, withPresence: true)

For more information, refer to the Publish and Subscribe and Message Publish sections of the documentation.

Next steps

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

Last updated on