SwiftSwift Native Configuration API Reference for Realtime Apps

 
These docs are for the new PubNub Swift SDK written purely in Swift. To view the docs for the older version (the PubNub Objective-C SDK wrapper for Swift), have a look here.

Swift complete API reference for building Realtime Applications on PubNub, including basic usage and sample code

To add the PubNub SDK to your project with Swift Package Manager, do the following:
  1. Create a new Xcode project.
    Create the project as a Single View App, using a Storyboard user interface.

    Xcode project setup
  2. 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 2.5.0 < 3.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 global PubNub object and pass it to your root view controller:

     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. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
    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()]
    
        let config = PubNubConfiguration(publishKey: "demo", subscribeKey: "demo")
        pubnub = PubNub(configuration: config)
    
        if #available(iOS 13.0, *) {
          // no-op - UI created in scene delegate
        } else if let rootVC = self.window?.rootViewController as? ViewController {
          rootVC.pubnub = pubnub
        }
    
        return true
      }
    
      // MARK: UISceneSession Lifecycle
    
      @available(iOS 13.0, *)
      func application(_ application: UIApplication,
                       configurationForConnecting connectingSceneSession: UISceneSession, 
                       options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
      }
    
      @available(iOS 13.0, *)
      func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // no-op
      }
    }
  7. If using multiple Scenes, use the SceneDelegate to pass your PubNub instance to your view controllers:

     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. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
    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, let pubnub = (UIApplication.shared.delegate as? AppDelegate)?.pubnub else { return }
        let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    
        let rootVC = mainStoryboard.instantiateInitialViewController() as? ViewController
        rootVC?.pubnub = pubnub
    
        let window = UIWindow(windowScene: windowScence)
        window.rootViewController = rootVC
        window.makeKeyAndVisible()
    
        self.window = window
      }
    }
  8. Set up your 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)")
        }
        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.timetoken.timetokenDate)" })
              }
            }
          case .failure(let error):
            print("Status Error: \(error.localizedDescription)")
          }
        }
    
        pubnub.add(listener)
    
        pubnub.subscribe(to: channels, withPresence: true)
      }
    }
This function is used for initializing the PubNub Client API context. This function must be called before attempting to utilize any API functionality in order to establish account level credentials such as publishKey and subscribeKey.
To Initialize Pubnub you can use the following method(s) in the Swift SDK:
  1. PropertyTypeRequiredDefaultsDescription
    publishKeyString?YesSpecifies the PubNub Publish Key to be used when publishing messages to a channel.
    subscribeKeyString?OptionalSpecifies the PubNub Subscribe Key to be used when subscribing to a channel.
    cipherKeyCrypto?OptionalIf set, all communication will be encrypted with this key.
    authKeyString?OptionalIf Access Manager (PAM) is enabled, client will use authKey on all requests.
    uuidStringYesSDK generated random UUID

    UUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub.

    Allowing the SDK to generate a random UUID can result in significant billing impacts, particularly on an MAU pricing plan.

    useSecureConnectionsBoolOptionaltrue If true, requests will be made over https, otherwise they will use http You will still need to disable ATS for the system to allow insecure network traffic. See Apple’s documentation for further details.
    originStringOptionalps.pndsn.comDomain name used for requests ps.pndsn.com.
    useInstanceIdBoolOptionalfalseWhether a PubNub object instanceId should be included on outgoing requests.
    useRequestIdBoolOptionalfalseWhether a request identifier should be included on outgoing requests.
    automaticRetryAutomaticRetry?OptionalReconnection policy which will be used if/when a request fails.
    urlSessionConfigurationURLSessionConfigurationOptional.pubnubURLSessionConfiguration used for URLSession network events.
    durationUntilTimeoutIntOptional300How long (in seconds) the server will consider the client alive for presence.
    - NOTE: The minimum value this field can be is 20.
    heartbeatIntervalUIntOptional0How often (in seconds) the client will announce itself to server.
    - NOTE: The minimum value this field can be is 0.
    supressLeaveEventsBoolOptionalfalseWhether to send out the leave requests.
    requestMessageCountThresholdUIntOptional100The number of messages into the payload before emitting RequestMessageCountExceeded.
    filterExpressionString?OptionalPSV2 feature to subscribe with a custom filter expression.
 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. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
var config = PubNubConfiguration(
  publishKey: "demo",
  subscribeKey: "demo"
)
config.uuid = "myUniqueUUID"

let pubnub = PubNub(configuration: config)
It returns the Pubnub instance for invoking PubNub APIs like publish(), subscribe(), fetchMessageHistory(), hereNow(), etc.
  1.  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. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
    var config = PubNubConfiguration(
      publishKey: "demo",
      subscribeKey: "demo"
    )
    config.uuid = "myUniqueUUID"
    let pubnub = PubNub(configuration: config)
  2. In the case where a client will only read messages and never publish to a channel, you can simply omit the publishKey when initializing the client:
     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. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
    var config = PubNubConfiguration(
      subscribeKey: "demo"
    )
    let pubnub = PubNub(configuration: config)
  3. Set a custom UUID to identify your users.
     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. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
    var config = PubNubConfiguration(
      subscribeKey: "mySubscribeKey",
      publishKey: "myPublishKey"
    )
    config.uuid = "myUniqueUUID"
    
    let pubnub = PubNub(configuration: config)
  4. This examples demonstrates how to enable PubNub Transport Layer Encryption with SSL. Just initialize the client with ssl set to true. The hard work is done, now the PubNub API takes care of the rest. Just subscribe and publish as usual and you are good to go.

     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. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
    var config = PubNubConfiguration(
      publishKey: "demo",
      subscribeKey: "demo"
    )
    config.uuid = "myUniqueUUID"
    
    let pubnub = PubNub(configuration: config)
This function provides the capability to reset a user's authKey.
Typically authKey is specified during initialization for PubNub Access Manager enabled applications. In the event that authKey has expired or a new authKey is issued to the client from a Security Authority, the new authKey can be sent using AuthKey().
To Set Authentication Key you can use the following method(s) in the Swift SDK
var config = PubNubConfiguration(
  publishKey: "demo",
  subscribeKey: "demo"
)
config.authKey = "my-new-authkey"

let pubnub = PubNub(configuration: config)
let authkey = config.authKey
// -- OR --
let authKey = pubnub.configuration.authKey
None.

Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
To set/get filters you can use the following property.
 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. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
var config = PubNubConfiguration(
  publishKey: "demo",
  subscribeKey: "demo"
)
config.filterExpression = "(senderID=='PubNub')"

let pubnub = PubNub(configuration: config)
let filter = config.filterExpression
// -- OR --
let filter = pubnub.configuration.filterExpression