Feedback

iOSiOSCocoaSwiftiOS Swift Configuration API Reference for Realtime Apps

Swift complete API reference for building Realtime Applications on PubNub, including basic usage and sample code.
PNConfiguration instance is storage for user-provided information which describe further PubNub client behaviour. Configuration instance contain additional set of properties which allow to perform precise PubNub client configuration.
To create configuration instance you can use the following function in the Swift SDK:
  1. ParameterTypeRequiredDescription
    publishKey StringYesYour PubNub Publish Key.
    subscribeKey StringYesYour PubNub Subscribe Key.
    heartbeatNotificationOptionsPNHeartbeatNotificationOptionsNo

    These are bitmask options, they can be combined. When client instances are notified about heartbeat operations, this happens through the PNObjectEventListener callback for statuses.

    PNHeartbeatNotifySuccess: explicitly tells client to notify on successful heartbeat operations.

    PNHeartbeatNotifyFailure: explicitly tells client to notify on failed heartbeat operations (default is only this option)

    PNHeartbeatNotifyAll: This is a combination of PNHeartbeatNotifySuccess and PNHeartbeatNotifyFailure

    PNHeartbeatNotifyNone: This means the client will not provide any callback notifications for heartbeat operations

    stripMobilePayloadBoolNoStores whether client should strip out received messages (real-time and history) from data which has been appended by client (like mobile payload for push notifications).
    cipherKeyStringNoKey which is used to encrypt messages pushed to PubNub service and decrypt messages received from live feeds on which client subscribed at this moment.
    subscribeMaximumIdleTimeTimeIntervalNo

    Maximum number of seconds which client should wait for events from live feed.

    Default 310.

    nonSubscribeRequestTimeoutTimeIntervalNo

    Number of seconds which is used by client during non-subscription operations to check whether response potentially failed with timeout or not.

    Default 10.

    presenceHeartbeatValueIntNoNumber of seconds which is used by server to track whether client still subscribed on remote data objects live feed or not.
    presenceHeartbeatIntervalIntNoNumber of seconds which is used by client to issue heartbeat requests to PubNub service.
    keepTimeTokenOnListChangeBoolNo

    Whether client should keep previous time token when subscribe on new set of remote data objects live feeds.

    Default true.

    catchUpOnSubscriptionRestoreBoolNo

    Whether client should try to catch up for events which occurred on previously subscribed remote data objects feed while client was off-line.

    Default true.

    applicationExtensionSharedGroupIdentifierStringNo

    Reference on group identifier which is used to share request cache between application extension and it's containing application.

    This property should be set to valid registered group only if PubNub client is used inside of application's extension (iOS 8.0+, macOS 10.10+).

    requestMessageCountThresholdUIntNoNumber of maximum expected messages from PubNub service in single response.
    maximumMessagesCacheSizeUIntNo

    Messages de-duplication cache size.

    Default 100.

    completeRequestsBeforeSuspensionBoolNo

    Whether client should try complete all API call which is done before application will be completely suspended.

    Default true.

let config = PNConfiguration(publishKey: "demo", subscribeKey: "demo")
self.client = PubNub.clientWithConfiguration(config)
self.client.addListener(self)
Configured and ready to use client configuration instance.
  1. let config = PNConfiguration(publishKey: "<pub key>", subscribeKey: "<sub key>")
    /**
     This is where you need to adjust the PNConfiguration object for the types of heartbeat notifications you want.
     This is a bitmask of options located at https://github.com/pubnub/objective-c/blob/1f1c7a41a3bd8c32b644a6ad98fe179d45397c2b/PubNub/Misc/PNStructures.h#L24
     */
    config.heartbeatNotificationOptions = [.notifyAll]
    
    self.client = PubNub.clientWithConfiguration(config)
    self.client.addListener(self)
  2. func client(_ client: PubNub, didReceive status: PNStatus) {
    		
    	if status.operation == .heartbeatOperation {
    		
    		/**
    		 Heartbeat operations can in fact have errors, so it is important to check first for an error.
    		 For more information on how to configure heartbeat notifications through the status 
    		 PNObjectEventListener callback, consult http://www.pubnub.com/docs/ios-objective-c/api-reference-configuration#configuration_basic_usage
    		 */
    		
    		if !status.isError { /* Heartbeat operation was successful. */ }
    		else { /* There was an error with the heartbeat operation, handle here. */ }
    	}
    }
PubNub client instance doesn’t allow dynamic configuration update, but it has helper functions which allow to receive new instance with updated configuration. Updated configuration will be applied on PubNub client copy. Original instance after copy block will return shouldn’t be used anymore.
To update client configuration you can use following functions in the Swift SDK:
  1. ParameterTypeRequiredDescription
    configuration
    PNConfiguration
    Yes
    Class Instance which stores the configuration settings which is used by the PubNub client.
    closure
    (PubNub) -> Void
    Yes
    Completion closure which is called at the end of update process, has one parameter - PubNub instance with updated configuration.
  2. ParameterTypeRequiredDescription
    configuration
    PNConfiguration
    Yes
    Class Instance which stores the configuration settings which is used by the PubNub client.
    callbackQueue
    dispatch_queue_t
    No
    The GCD dispatch queue where callbacks and completion handlers will be called (asynchronously).
    closure
    (PubNub) -> Void
    Yes
    Completion closure which is called at the end of update process, has one parameter - PubNub instance with updated configuration.
// User authorized and we need to update used UUID
let configuration = self.client.currentConfiguration()
configuration.uuid = "AuthorizedUserID"
self.client.copyWithConfiguration(configuration, completion: { (updatedClient) in

	// Store reference on new client with updated configuration.
	self.client = updatedClient
})
Void
Install the CocoaPods gem by following the procedure defined under How to Get It.
To add the PubNub SDK to your project with CocoaPods, there are four tasks to complete:
  1. Create new Xcode project.

    Xcode project

  2. Create a Podfile in your newly created Xcode project root folder
    touch Podfile
  3. The PubNub client can be added as module (only with a deployment target of iOS 8.0 and above) or as a static library (for deployment targets of iOS 7.0 and above).
    1. For a deployment target of iOS 8.0 and above use:
      source 'https://github.com/CocoaPods/Specs.git'
      
      # optionally complete and uncomment if compilation issues arise
      # project '<path to project relative to this Podfile>/<name of project without extension>'
      # workspace 'MyPubNubProject'
      
      use_frameworks!
      
      target 'application-target-name' do
          # Should only use this with projects 
          # that must have a minimum deployment 
          # target of iOS 8 
          platform :ios, '8.0' # (or '9.0' or '10.0')
          pod "PubNub", "~> 4"
      end
    2. For a deployment target of iOS 7.0 and above use:
      source 'https://github.com/CocoaPods/Specs.git'
      
      # optionally complete and uncomment if compilation issues arise
      # project '<path to project relative to this Podfile>/<name of project without extension>'
      # workspace 'MyPubNubProject'
       
      target 'application-target-name' do
          # Should only use this with projects 
          # that must have a minimum deployment 
          # target of iOS 7 
          platform :ios, '7.0' # (if you don't need to use iOS 7, then see other Podfile)
          pod "PubNub", "~> 4"
      end
      If you have any other pods you'd like to include, or if you have other targets you'd to add (like a test target) add those entries to this Podfile as well. See the CocoaPods documentation for more information on Podfile configuration.
  4. Install your pods by running pod install via the command line from the directory that contains your Podfile.

 
After installing your Pods, you should only be working within the workspace generated by CocoaPods or specified by you in Podfile. Always open the newly generated workspace file, not the original project file!

By creating the Podfile and running pod install in the same directory as your Podfile, you should now have a Swift project with the PubNub SDK installed. To access the PubNub Objective-C SDK with the deployment target set to iOS 7.0 and below, you will need to create a bridging header.
The bridging header is a way to make the Swift code aware of the available Objective-C interface to the PubNub client. To create your bridging header:
  1. Create a new File (File → New → File) of type Source → Header File

    Create a new File

  2. Specify a location and name (along the lines of [MyProjectName]-Bridging-Header.h) and create the file

    Specify a location and name

  3. Make your project aware of this newly created bridging header by opening your project, selecting Build Settings, and using the search box to find Objective-C Bridging Header

    Objective-C Bridging Header

  4. Specify the path to the bridging header. The location is relative to the project / workspace files location.

    Specify the path to the bridging header

  5. Select your bridging file from project tree (replace if new, add if existing) with:
    #import <PubNub/PubNub.h>
    The convention for bridging headers in Swift is to use a single bridging header file per project -- if you have other Pods included in your project that are written in Objective-C, they would be imported here as well.
If the project’s deployment target is set to iOS 8.0 and above, you will need to import the module named AppDelegate.swift:
import UIKit
import PubNub // <- Here is our PubNub module import.
	
class AppDelegate: UIResponder, UIApplicationDelegate, PNObjectEventListener {

	// Stores reference on PubNub client to make sure what it won't be released.
	var client: PubNub!

	func application(_ application: UIApplication, 
					 didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
		...
	}
}
	
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. ParameterTypeRequiredDescription
    configuration
    PNConfiguration
    Yes
    Class Instance which stores the configuration settings which is used by the PubNub client.
  2. ParameterTypeRequiredDescription
    configuration
    PNConfiguration
    Yes
    Class Instance which stores the configuration settings which is used by the PubNub client.
    callbackQueue
    dispatch_queue_t
    No
    The GCD dispatch queue where callbacks and completion handlers will be called (asynchronously).
let configuration = PNConfiguration(publishKey: "demo", subscribeKey: "demo")
configuration.TLSEnabled = true
self.client = PubNub.clientWithConfiguration(configuration)
It returns the Pubnub instance for invoking PubNub APIs like publish(), subscribeToChannels(), historyForChannel, hereNowForChannel, etc.
  1. let configuration = PNConfiguration(publishKey: "demo", subscribeKey: "demo")
    self.client = PubNub.clientWithConfiguration(configuration)
  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:
    let configuration = PNConfiguration(publishKey: "", subscribeKey: "demo")
    self.client = PubNub.clientWithConfiguration(configuration)
  3. Under certain circumstances it useful to use a custom UUID to help in identifying your users.
    let configuration = PNConfiguration(publishKey: "demo", subscribeKey: "demo")
    configuration.uuid = "Stephen"
    self.client = PubNub.clientWithConfiguration(configuration)
  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.

    let configuration = PNConfiguration(publishKey: "demo", subscribeKey: "demo")
    configuration.TLSEnabled = true
    self.client = PubNub.clientWithConfiguration(configuration)
This function is used to set a user ID on the fly.
To set UUID you can use the following method(s) in Swift SDK:
  1. open var uuid: String
// User authorized and we need to update used UUID
let configuration = self.client.currentConfiguration()
configuration.uuid = NSUUID().uuidString
self.client.copyWithConfiguration(configuration, completion: { (updatedClient) in

	// Store reference on new client with updated configuration.
	self.client = updatedClient
})
  1. /**
     Subscription process results arrive to listener which should adopt to PNObjectEventListener protocol
     and registered using:
     */
    self.client.addListener(self)
    self.client.subscribeToChannels([NSUUID().uuidString], withPresence: false)
    
    
    // Handle new message from one of channels on which client has been subscribed.
    func client(_ client: PubNub, didReceiveMessage message: PNMessageResult) {
    		
    	// Handle new message stored in message.data.message
    	if message.data.channel != 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.
    	}
    	
    	print("Received message: \(message.data.message) on channel \(message.data.channel) " +
    		  "at \(message.data.timetoken)")
    }
    
    // Handle subscription status change.
    func client(_ client: PubNub, didReceive status: PNStatus) {
    	
    	if status.operation == .subscribeOperation {
    		
    		// Check whether received information about successful subscription or restore.
    		if status.category == .PNConnectedCategory || status.category == .PNReconnectedCategory {
    			
    			let subscribeStatus: PNSubscribeStatus = status as! PNSubscribeStatus
    			if subscribeStatus.category == .PNConnectedCategory {
    				
    				// This is expected for a subscribe, this means there is no error or issue whatsoever.
    			}
    			else {
    				
    				/**
    				 This usually occurs if subscribe temporarily fails but reconnects. This means there was 
    				 an error but there is no longer any issue.
    				 */
    			}
    		}
    		else if status.category == .PNUnexpectedDisconnectCategory {
    			
    			/**
    			 This is usually an issue with the internet connection, this is an error, handle 
    			 appropriately retry will be called automatically.
    			 */
    		}
    		// Looks like some kind of issues happened while client tried to subscribe or disconnected from 
    		// network.
    		else {
    			
    			let errorStatus: PNErrorStatus = status as! PNErrorStatus
    			if errorStatus.category == .PNAccessDeniedCategory {
    				
    				/**
    				 This means that PAM does allow this client to subscribe to this channel and channel group 
    				 configuration. This is another explicit error.
    				 */
    			}
    			else {
    				
    				/**
    				 More errors can be directly specified by creating explicit cases for other error categories 
    				 of `PNStatusCategory` such as: `PNDecryptionErrorCategory`,  
    				 `PNMalformedFilterExpressionCategory`, `PNMalformedResponseCategory`, `PNTimeoutCategory`
    				 or `PNNetworkIssuesCategory`
    				 */
    			}
    		}
    	}
    }
  2. let configuration = self.client.currentConfiguration()
    configuration.uuid = "my_custom_uuid"
    self.client.copyWithConfiguration(configuration, completion: { (updatedClient) in
     
    	// Store reference on new client with updated configuration.
    	self.client = updatedClient
    })
  3. let configuration = self.client.currentConfiguration()
    configuration.authKey = NSUUID().uuidString
    self.client.copyWithConfiguration(configuration, completion: { (updatedClient) in
    
    	// Store reference on new client with updated configuration.
    	self.client = updatedClient
    })
Setter and getter for users auth key.
let configuration = self.client.currentConfiguration()
configuration.authKey = "my_new_authkey"
self.client.copyWithConfiguration(configuration, completion: { (updatedClient) in

	// Store reference on new client with updated configuration.
	self.client = updatedClient
})
// Request current client configuration and pull out authorisation key from it.
let authKey = self.client.currentConfiguration().authKey
Get Auth key returns the current authentication key.
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 methods.
let configuration = PNConfiguration(publishKey: "demo", subscribeKey: "demo")
self.client = PubNub.clientWithConfiguration(configuration)
self.client.filterExpression = "(senderID=='PubNub')";
print("Filtering expression: \(self.client.filterExpression)")
Get Filter Expression returns the Current filtering expression.

Set Filter Expression:

 
If filter expression is malformed, PNObjectEventListener won't receive any messages and presence events from service (only error status).

Go to Publish & Subscribe