Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@ajb413
Created January 29, 2019 07:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajb413/90a0a6c01b0e725f8de1a9d8924f37e8 to your computer and use it in GitHub Desktop.
Save ajb413/90a0a6c01b0e725f8de1a9d8924f37e8 to your computer and use it in GitHub Desktop.
PubNub Pub/Sub Swift Quickstart

Swift

Open Xcode and Create a new Xcode project with Single View App called pubnubdemo.

Quit Xcode and navigate to the project directory in the terminal using this command.

cd pubnubdemo

Install CocoaPods, then use the pod command to create a Podfile.

pod init

In this directory, replace all of the text in the Podfile with the following, then save the file.

use_frameworks!

target 'pubnubdemo' do
  platform :ios, '11.0'
  pod 'PubNub', '~>4.6'
end

Install the PubNub SDK with CocoaPods.

pod install

Or - get the SDK with Carthage.

github "pubnub/objective-c" ~> 4.6

Open Xcode from the terminal using this command.

open pubnubdemo.xcworkspace

Click the Folder icon on the left and open pubnubdemo/pubnubdemo/ViewController.swift.

Paste this code into the ViewController.swift file.

import UIKit
import PubNub

class ViewController: UIViewController, PNObjectEventListener {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let client: PubNub?
        let config = PNConfiguration(
            publishKey: "YOUR PUBNUB PUBLISH KEY HERE",
            subscribeKey: "YOUR PUBNUB SUBSCRIBE KEY HERE"
        )
        
        config.stripMobilePayload = false
        
        client = PubNub.clientWithConfiguration(config)
        client?.addListener(self)
        
        client?.timeWithCompletion({(result,status) -> Void in
            if status == nil {
                client?.publish("Hellloo From Swift SDK", toChannel: "pubnub_onboarding_channel") {
                    (status) in
                    print("I published with: \(status.debugDescription)")
                }
            }
        })
    }
}

This page is subscribed. Build and run your app in an emulator or on an iOS device to see the publish here - in real time.

[Subscribed Log Area Here]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment