Configuration API for PubNub Swift Native SDK

Migration guide

The PubNub Swift 3.0 SDK contains many significant changes from the 2.x SDK, including breaking changes. Please refer to the PubNub Swift 3.0 Migration Guide for more details.

A configuration object that defines behavior and policies for a PubNub instance.

Initializer(s)

Creates a configuration using the specified PubNub Publish and Subscribe Keys:

Method(s)

To Initialize PubNub, you can use the following method(s) in the Swift SDK:

PubNubConfiguration(publishKey: String?, subscribeKey: String?)
ParameterTypeRequiredDefaultDescription
publishKeyString?OptionalnilSpecifies the PubNub Publish Key to be used when publishing messages to a channel.
subscribeKeyString?YesnilSpecifies the PubNub Subscribe Key to be used when subscribing to a channel.
cipherKeyCrypto?OptionalnilIf set, all communication will be encrypted with this key.
authKeyStringOptionalnilIf Access Manager is enabled, client will use authKey on all requests.
userIdStringYesuserId to use. You should set a unique identifier for the user or the device that connects to PubNub.

It's a UTF-8 encoded string of up to 64 alphanumeric characters.

If you don't set the userId, you won't be able to connect to PubNub.
useSecureConnectionsBoolOptionaltrueIf 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.
originStringOptional"ps.pndsn.com"Domain name used for requests.
useInstanceIdBoolOptionalfalseWhether a PubNub object instanceId should be included on outgoing requests.
automaticRetryAutomaticRetry?OptionalnilReconnection policy which will be used if/when a request fails.
urlSessionConfigurationURLSessionConfigurationYesURLSessionConfiguration.pubnubURLSessionConfiguration used for URLSession network events.
durationUntilTimeoutIntOptional300How long (in seconds) the server will consider the client alive for presence. Minimum value is 20.
heartbeatIntervalUIntOptional0How often (in seconds) the client will announce itself to server. Minimum value is 0.
suppressLeaveEventsBoolOptionalfalseWhether to send out the leave requests.
requestMessageCountThresholdUIntOptional100The number of messages into the payload before emitting RequestMessageCountExceeded.
filterExpressionString?OptionalnilPSV2 feature to subscribe with a custom filter expression.
uuidStringYesThis parameter is deprecated, use userId instead.

UUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub. If you don't set the UUID, you won't be able to connect to PubNub.

Basic Usage

Initialize the PubNub client API

Required userId

Always set the userId to uniquely identify the user or device that connects to PubNub. This userId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the userId, you won't be able to connect to PubNub.

let config = PubNubConfiguration(
publishKey: "demo",
subscribeKey: "demo",
userId: "myUniqueUserId"
)

let pubnub = PubNub(configuration: config)

Other Examples

Initialization for a Read-Only client

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:

Required userId

Always set the userId to uniquely identify the user or device that connects to PubNub. This userId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the userId, you won't be able to connect to PubNub.

let config = PubNubConfiguration(
subscribeKey: "demo",
userId: "myUniqueUserId"
)
let pubnub = PubNub(configuration: config)

Event Listeners

You can be notified of connectivity status, message, and presence notifications via the listeners.

Listeners should be added before calling the method.

Add Listeners

// Create a new listener instance
let listener = SubscriptionListener()

// Add listener event callbacks
listener.didReceiveSubscription = { event in
switch event {
case let .messageReceived(message):
print("Message Received: \(message) Publisher: \(message.publisher ?? "defaultUUID")")
case let .connectionStatusChanged(status):
print("Status Received: \(status)")
case let .presenceChanged(presence):
print("Presence Received: \(presence)")
case let .subscribeError(error):
print("Subscription Error \(error)")
default:
show all 21 lines
How to check UUID

You can check the UUID of the publisher of a particular message by checking the message.publisher property in the subscription listener.

Remove Listeners

The SubscriptionListener can be removed by either calling listener.cancel(), or by letting it fall out of scope and be removed as an autoreleased object.

Listener Subscription Events

This is the list of SubscriptionEvent case types that can be emitted from didReceiveSubscription, or grouped together using didReceiveBatchSubscription. Each event case also has a standalone listener that can save code space, but will be functionally equivalent to using didReceiveSubscription.

SubscriptionEvent CaseEvent TypeStandalone ListenerEvent Description
messageReceivedPubNubMessagedidReceiveMessageMessages sent to subscribed channels/groups
signalReceivedPubNubMessagedidReceiveSignalSignals sent to subscribed channels/groups
connectionStatusChangedConnectionStatusdidReceiveStatusChanges in the connection to the PubNub system
subscriptionChangedSubscriptionChangeEventdidReceiveSubscriptionChangeNotifies when channels/groups are subscribed or unsubscribed
presenceChangedPubNubPresenceChangedidReceivePresencePresence changes on subscribed channels/groups tracking presence
uuidMetadataSetPubNubUUIDMetadataChangesetdidReceiveObjectMetadataEventUUID metadata was set
uuidMetadataRemovedStringdidReceiveObjectMetadataEventUUID metadata was removed
channelMetadataSetPubNubChannelMetadataChangesetdidReceiveObjectMetadataEventChannel metadata was set
channelMetadataRemovedStringdidReceiveObjectMetadataEventChannel metadata was removed
membershipMetadataSetPubNubMembershipMetadatadidReceiveObjectMetadataEventMembership metadata was set
membershipMetadataRemovedPubNubMembershipMetadatadidReceiveObjectMetadataEventMembership metadata was removed
messageActionAddedPubNubMessageActiondidReceiveMessageActionA PubNubMessageAction was added to a published message
messageActionRemovedPubNubMessageActiondidReceiveMessageActionA PubNubMessageAction was removed from a published message
subscribeErrorPubNubErrorsubscribeErrorAny error that might have occurred during the subscription stream

Basic Usage

This is an example using didReceiveBatchSubscription, to allow you to receive multiple events per event call.

listener.didReceiveBatchSubscription = { events in
for event in events {
switch event {
case .messageReceived(let message):
print("The \(message.channel) channel received a message at \(message.published)")
if let subscription = message.subscription {
print("The channel-group or wildcard that matched this channel was \(subscription)")
}
print("The message is \(message.payload) and was sent by \(message.publisher ?? "")")
case .signalReceived(let signal):
print("The \(signal.channel) channel received a message at \(signal.published)")
if let subscription = signal.subscription {
print("The channel-group or wildcard that matched this channel was \(subscription)")
}
print("The signal is \(signal.payload) and was sent by \(signal.publisher ?? "")")
show all 79 lines

Other Examples

For didReceiveSubscription, simply rename the remove the for...in loop while keeping the event switch:

listener.didReceiveSubscription = { event in
switch event {
// Same content as the above example
}
}

Overriding PubNub Configuration

All PubNubConfiguration properties are mutable, and can be changed after the object has been initialized. However, once the configuration is set on a PubNub instance those configurations are locked and can't be changed. Any changes would require a creating new PubNub instance.

userId

var config = pubnub.configuration
config.userId = "my_new_userId"

let pubnub = PubNub(configuration: config)

Authentication

var config = pubnub.configuration
config.authKey = "my_new_authkey"

let pubnub = PubNub(configuration: config)

Filter

You can override the filter expression without creating a new PubNub instance in one of two ways.

Equivalent functionality

These are functionally equivalent and will take effect on the next subscription request and persist until changed.

  1. In combination with a subscribe change:

    pubnub.subscribe(to: ["new_subscription"], filterOverride: "(senderID=='my_new_userId')")
  2. Without needing to make a subscription change:

    pubnub.subscribeFilterExpression = "(senderID=='my_new_userId')"
Last updated on