Publish/Subscribe API for PubNub Swift Native SDK

The foundation of the PubNub service is the ability to send a message and have it delivered anywhere in less than 100ms. Send a message to just one other person, or broadcast to thousands of subscribers at once.

For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.

Publish

publish() sends a message to all channel subscribers. A successfully published message is replicated across PubNub's points of presence and sent simultaneously to all subscribed clients on a channel. All publish calls are performed asynchronously.

ObjectNode

The new Jackson parser does not recognize JSONObject. Use ObjectNode instead.

  • You must initialize PubNub with the publishKey.
  • You don't have to be subscribed to a channel to publish to it.
  • You cannot publish to multiple channels simultaneously.

Method(s)

To Publish a message you can use the following method(s) in the Swift SDK:

publish(
channel: String,
message: JSONCodable,
shouldStore: Bool? = nil,
storeTTL: Int? = nil,
meta: AnyJSON? = nil,
shouldCompress: Bool = false,
customMessageType: String? = nil,
custom requestConfig: RequestConfiguration = RequestConfiguration(),
completion: ((Result<Timetoken, Error>) -> Void)?
)
ParameterTypeRequiredDefaultDescription
channelStringYesThe channel to publish to.
messageJSONCodableYesThe message to publish.
shouldStoreBool?OptionalnilIf true the published message is stored in history.
storeTTLInt?OptionalnilSet a per message time to live in Message Persistence. 1. If shouldStore = true, and storeTTL = 0, the message is stored with no expiry time. 2. If shouldStore = true and storeTTL = X (X is an Integer value), the message is stored with an expiry time of X hours. 3. If shouldStore is false or not specified, the message isn't stored and the storeTTL parameter is ignored. 4. If storeTTL isn't specified, then expiration of the message defaults back to the expiry value for the key.
metaJSONCodable?OptionalnilPublish extra meta with the request.
shouldCompressBoolOptionalfalseWhen true, the SDK uses HTTP POST to publish the messages. The message is sent in the BODY of the request, instead of the query string when HTTP GET is used. Also the messages are compressed thus reducing the size of the messages.
customMessageTypeStringOptionalA case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn-.

Examples: text, action, poll.
customRequestConfigurationOptionalRequestConfiguration()An object that allows for per-request customization of PubNub Configuration or Network Session
completion((Result<Timetoken, Error>) -> Void)?OptionalnilThe async Result of the method call

Completion Handler Result

Success

The Timetoken of the published Message.

Failure

An Error describing the failure.

Basic Usage

Publish a message to a channel

pubnub.publish(
channel: "my-channel",
message: "Hello from PubNub Swift SDK",
customMessageType: "text-message"
) { result in
switch result {
case let .success(timetoken):
print("Message Successfully Published at: \(timetoken)")
case let .failure(error):
print("Failed Response: \(error.localizedDescription)")
}
}
Subscribe to the channel

Before running the above publish example, either using the Debug Console or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.

Other Examples

Publish a Dictionary object

/*
Publish payload JSON equivalent to:
{
"greeting": "hello",
"location": "right here"
}
*/
pubnub.publish(
channel: "my_channel",
message: ["greeting": "hello", "location": "right here"]
) { result in
switch result {
case let .success(timetoken):
print("Message Successfully Published at: \(timetoken)")
case let .failure(error):
show all 18 lines

Publish the above Dictionary as a custom Swift Object

// Ensure that your custom object implements `JSONCodable`
struct Message: Codable, JSONCodable {
var greeting: String
var location: String
}

/*
Publish payload JSON equivalent to:
{
"greeting": "hello",
"location": "right here"
}
*/
pubnub.publish(channel: "my_channel", message: Message(greeting: "hello", location: "right here")) { result in
switch result {
show all 21 lines

Mix and match types with custom objects

struct Location: Codable, JSONCodable {
var lat: Double
var long: Double
}

struct Message: Codable, JSONCodable {
var greeting: String
var location: Location
}

/*
Publish payload JSON equivalent to:
{
"greeting": "hello",
"location": {
show all 33 lines

Publish an APNs2 push notification

let pushMessage = PubNubPushMessage(
apns: PubNubAPNSPayload(
aps: APSPayload(alert: .object(.init(title: "Apple Message")), badge: 1, sound: .string("default")),
pubnub: [.init(targets: [.init(topic: "com.pubnub.swift", environment: .production)], collapseID: "SwiftSDK")],
payload: "Push Message from PubNub Swift SDK"
),
fcm: PubNubFCMPayload(
payload: "Push Message from PubNub Swift SDK",
target: .topic("com.pubnub.swift"),
notification: FCMNotificationPayload(title: "Android Message"),
android: FCMAndroidPayload(collapseKey: "SwiftSDK", notification: FCMAndroidNotification(sound: "default"))
),
additional: "Push Message from PubNub Swift SDK"
)

show all 26 lines

Root level push message object

public struct PubNubPushMessage: JSONCodable {
/// The payload delivered via Apple Push Notification service (APNS)
public let apns: PubNubAPNSPayload?

/// The payload delivered via Firebase Cloud Messaging service (FCM)
public let fcm: PubNubFCMPayload?

/// Additional message payload sent outside of the push notification
///
/// In order to guarantee valid JSON any scalar values will be assigned to the `data` key.
/// Non-scalar values will retain their coding keys.
public var additionalMessage: JSONCodable?
}

Fire

The fire endpoint allows the client to send a message to Functions Event Handlers and Illuminate. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire() isn't replicated, and so won't be received by any subscribers to the channel. The message is also not stored in history.

Method(s)

To Fire a message you can use the following method(s) in the Swift SDK:

fire(
channel: String,
message: JSONCodable,
meta: JSONCodable? = nil,
custom requestConfig: RequestConfiguration = RequestConfiguration(),
completion: ((Result<Timetoken, Error>) -> Void)?
)
ParameterTypeRequiredDefaultDescription
channelStringYesThe channel to fire to.
messageJSONCodableYesThe message to fire.
metaJSONCodable?OptionalnilPublish extra meta with the request.
customRequestConfigurationOptionalRequestConfiguration()An object that allows for per-request customization of PubNub Configuration or Network Session
completion((Result<Timetoken, Error>) -> Void)?OptionalnilThe async Result of the method call

Completion Handler Result

Success

The Timetoken of the published Message.

Failure

An Error describing the failure.

Basic Usage

Fire a message to a channel

pubnub.fire(
channel: "my-channel",
message: "Hello from PubNub Swift SDK"
) { result in
switch result {
case let .success(timetoken):
print("Message Successfully Published at: \(timetoken)")
case let .failure(error):
print("Failed Response: \(error.localizedDescription)")
}
}

Signal

The signal() function is used to send a signal to all subscribers of a channel.

By default, signals are limited to a message payload size of 64 bytes. This limit applies only to the payload, and not to the URI or headers. If you require a larger payload size, please contact support.

Method(s)

To Signal a message you can use the following method(s) in the Swift SDK:

signal( 
channel: String,
message: JSONCodable,
customMessageType: String? = nil,
custom requestConfig: RequestConfiguration = RequestConfiguration(),
completion: ((Result<Timetoken, Error>) -> Void)?
)
ParameterTypeRequiredDefaultDescription
channelStringYesThe channel to send a signal to.
messageJSONCodableYesThe message to signal.
customMessageTypeStringOptionalA case-sensitive, alphanumeric string from 3 to 50 characters describing the business-specific label or category of the message. Dashes - and underscores _ are allowed. The value cannot start with special characters or the string pn_ or pn-.

Examples: text, action, poll.
customRequestConfigurationOptionalRequestConfiguration()An object that allows for per-request customization of PubNub Configuration or Network Session
completion((Result<Timetoken, Error>) -> Void)?OptionalnilThe async Result of the method call

Completion Handler Result

Success

The Timetoken of the published Message.

Failure

An Error describing the failure.

Basic Usage

Signal a message to a channel

pubnub.signal(
channel: "my-channel",
message: "Hello from PubNub Swift SDK",
customMessageType: "text-message-signalled"
) { result in
switch result {
case let .success(timetoken):
print("Message Successfully Published at: \(timetoken)")
case let .failure(error):
print("Failed Response: \(error.localizedDescription)")
}
}

Subscribe

The subscribe function creates an open TCP socket to PubNub and begins listening for messages and events on a specified entity or set of entities. To subscribe successfully, you must configure the appropriate subscribeKey at initialization.

Entities are first-class citizens that provide access to their encapsulated APIs. You can subscribe using the PubNub client object or directly on a specific entity:

A newly subscribed client receives messages after the subscribe() call completes. You can configure automaticRetry to attempt to reconnect automatically and retrieve any available messages if a client gets disconnected (stops all real-time data flow but might not necessarily remove subscriptions or affect the state of subscribed channels).

Subscription scope

Subscription objects provide an interface to attach listeners for various real-time update types. Your app receives messages and events via those event listeners. Two types of subscriptions are available:

  • Subscription, created from an entity with a scope of only that entity (for example, a particular channel)
  • SubscriptionSet, created from the PubNub client with a global scope (for example, all subscriptions created on a single pubnub object ). A subscription set can have one or more subscriptions.

The event listener is a single point through which your app receives all the messages, signals, and events in the entities you subscribed to. For information on adding event listeners, refer to Event listeners.

Create a subscription

An entity-level Subscription allows you to receive messages and events for only that entity for which it was created. Using multiple entity-level Subscriptions is useful for handling various message/event types differently in each channel.

Keep a strong reference

You should keep a strong reference to every created subscription/subscription set because they must stay in memory to listen for updates. If you were to create a Subscription/SubscriptionSet and not keep a strong reference to it, Automatic Reference Counting (ARC) could deallocate the Subscription as soon as your code finishes executing.

// Entity-based, local-scoped
let subscription = client.channel(String).subscription(options)
ParameterTypeRequiredDescription
optionsSubscriptionOptionsNoSubscription behavior configuration.

Create a subscription set

A client-level SubscriptionSet allows you to receive messages and events for all entities. A single SubscriptionSet is useful for similarly handling various message/event types in each channel.

Keep a strong reference

You should keep a strong reference to every created subscription/subscription set because they must stay in memory to listen for updates. If you were to create a Subscription/SubscriptionSet and not keep a strong reference to it, Automatic Reference Counting (ARC) could deallocate the Subscription as soon as your code finishes executing.

// Client-based, general-scoped
pubnub.subscription(
queue: DispatchQueue = .main,
entities: any Collection<Subscribable>,
options: SubscriptionOptions = SubscriptionOptions.empty()
)
ParameterTypeRequiredDescription
queueDispatchQueueNoAn underlying queue to dispatch events. Defaults to the main queue.
entitiesCollection<Subscribable>YesOne or more entities to create a subscription of. Available values include: ChannelRepresentation, ChannelGroupRepresentation, UserMetadataRepresentation, ChannelMetadataRepresentation.
optionsSubscriptionOptionsNoSubscription behavior configuration.
Add/remove sets

You can add and remove subscriptions to create new sets. Refer to the Other examples section for more information.

SubscriptionOptions

SubscriptionOptions is a class. Available properties include:

OptionDescription
ReceivePresenceEventsWhether presence updates for userId should be delivered through the listener streams.

Method(s)

Subscription and SubscriptionSet use the same subscribe() method.

Subscribe

To subscribe, you can use the following method in the Swift SDK:

subscription.subscribe(with: Timetoken? = nil)
ParameterTypeRequiredDescription
withTimetokenNoTimetoken from which to return any available cached messages. Message retrieval with timetoken is not guaranteed and should only be considered a best-effort service.

If the value is not a 17-digit number, the provided value will be ignored.
Basic usage
let subscription1 = pubnub.channel("channelName").subscription()
subscription1.subscribe()

let subscriptionSet = pubnub.subscription(
entities: [
pubnub.channel("channel"),
pubnub.channelGroup("channelGroup"),
pubnub.userMetadata("userMetadataIdentifier")
],
options: ReceivePresenceEvents()
)

subscriptionSet.subscribe()
Other examples
Create a subscription set from 2 individual subscriptions
// Create a subscription from a channel entity
let subscription1 = pubnub.channel("channelName").subscription()

// Create a subscription from a channel group entity
let subscription2 = pubnub.channelGroup("channelGroupName").subscription()

// Create a subscription set from individual entities
let subscriptionSet = SubscriptionSet(subscriptions: [subscription1, subscription2])

// Add another subscription to the set
subscriptionSet.add(subscription: sub3)

// Remove a subscription from the set
subscriptionSet.remove(subscription: sub3)
Returns

The subscribe() method doesn't have a return value.

Entities

Entities are subscribable objects for which you can receive real-time updates (messages, events, etc).

Create channels

This method returns a local ChannelRepresentation entity.

pubnub.channel(String)
ParameterTypeRequiredDescription
channelStringYesThe name of the channel to create a subscription of.

Basic usage

pubnub.channel("channelName")

Create channel groups

This method returns a local ChannelGroupRepresentation entity.

pubnub.channelGroup(String)
ParameterTypeRequiredDescription
channelGroupStringYesThe name of the channel group to create a subscription of.

Basic usage

pubnub.channelGroup("channelGroupName")

Create channel metadata

This method returns a local ChannelMetadataRepresentation entity.

pubnub.channelMetadata(String)
ParameterTypeRequiredDescription
channel_metadataStringYesThe String identifier of the channel metadata object to create a subscription of.

Basic usage

pubnub.channelMetadata("channelMetadata")

Create user metadata

This method returns a local UserMetadataRepresentation entity.

pubnub.userMetadata(String)
ParameterTypeRequiredDescription
userMetadataStringYesThe String identifier of the user metadata object to create a subscription of.

Basic usage

pubnub.userMetadata("userMetadata")

Event listeners

Messages and events are received in your app using a listener. This listener allows a single point to receive all messages, signals, and events.

You can attach listeners to the instances of Subscription, SubscriptionSet, and, in the case of the connection status, the PubNub client.

Add listeners

You can implement multiple listeners with the onEvent closure or register an event-specific listener that receives only a selected type, like message or file.

Method(s)

// Add event-specific listeners
// Add a listener to receive Message changes
subscription.onMessage = { message in
print("Message Received: \(message) Publisher: \(message.publisher ?? "defaultUUID")")
}

// Add a listener to receive Presence changes
// requires a subscription with presence
subscription.onPresence = { presenceChange in
for action in presenceChange.actions {
switch action {
case let .join(uuids):
print("The following list of occupants joined at \(presenceChange.timetoken): \(uuids)")
case let .leave(uuids):
print("The following list of occupants left at \(presenceChange.timetoken): \(uuids)")
show all 82 lines

Basic usage

let subscription1 = pubnub.channel("channelName").subscription()

let subscriptionSet = pubnub.subscription(
entities: [
pubnub.channel("channel"),
pubnub.channelGroup("channelGroup"),
pubnub.userMetadata("userMetadataIdentifier")
],
options: ReceivePresenceEvents()
)

subscription1.onEvent = { event in
switch event {
case let .messageReceived(message):
print("Message Received: \(message) Publisher: \(message.publisher ?? "defaultUUID")")
show all 40 lines

Add connection status listener

The PubNub client has a listener dedicated to handling connection status updates.

Client scope

This listener is only available on the PubNub object.

Method(s)

pubnub.onConnectionStateChange: ((ConnectionStatus) -> Void)?

Basic usage

pubnub.onConnectionStateChange = { newStatus in
print("Connection Status: \(newStatus)")
}

Returns

The subscription status. For information about available statuses, refer to SDK statuses.

Clone

Create a clone of an existing subscription with the same subscription state but an empty list of real-time event listeners.

Method(s)

subscription.clone()

subscriptionSet.clone()

Basic Usage

let subscriptionSet = pubnub.subscription(
entities: [
pubnub.channel("channel"),
pubnub.channelGroup("channelGroup"),
pubnub.userMetadata("userMetadataIdentifier")
],
options: ReceivePresenceEvents()
)

let subscription1 = pubnub.channel("channelName").subscription()

let subscriptionSetClone = subscriptionSet.clone()
let subscription2 = subscription1.clone()

Returns

A new instance of the subscription object with an empty event dispatcher.

Unsubscribe

Stop receiving real-time updates from a Subscription or a SubscriptionSet.

Method(s)

subscription.unsubscribe()

subscriptionSet.unsubscribe()

Basic Usage

let subscriptionSet = pubnub.subscription(
entities: [
pubnub.channel("channel"),
pubnub.channelGroup("channelGroup"),
pubnub.userMetadata("userMetadataIdentifier")
],
options: ReceivePresenceEvents()
)

let subscription1 = pubnub.channel("channelName").subscription()

subscriptionSet.subscribe()
subscription1.subscribe()

subscriptionSet.unsubscribe()
show all 16 lines

Returns

None

Unsubscribe All

Remove the client's active subscriptions from all channels. It clears out the list of channels the client is currently listening to.

Client scope

This method is only available on the PubNub object.

Method(s)

pubnub.unsubscribeAll()

Basic Usage

let subscriptionSet = pubnub.subscription(
entities: [
pubnub.channel("channel"),
pubnub.channelGroup("channelGroup"),
pubnub.userMetadata("userMetadataIdentifier")
],
options: ReceivePresenceEvents()
)

let subscription1 = pubnub.channel("channelName").subscription()

subscriptionSet.subscribe()
subscription1.subscribe()

pubnub.unsubscribeAll()

Returns

None

Subscribe (deprecated)

Deprecated

This method is deprecated. Use Subscribe instead.

Receive messages

Your app receives messages and events via event listeners. The event listener is a single point through which your app receives all the messages, signals, and events that are sent in any channel you are subscribed to.

For more information about adding a listener, refer to the Event Listeners section.

Description

This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel. To subscribe to a channel the client must send the appropriate subscribeKey at initialization.

By default a newly subscribed client will only receive messages published to the channel after the subscribe() call completes.

Connectivity notification

You can be notified of connectivity via the connect callback. By waiting for the connect callback to return before attempting to publish, you can avoid a potential race condition on clients that subscribe and immediately publish messages before the subscribe has completed.

The PubNub Swift SDK removes (dedupes) messages automatically if they have the same timetoken, publisher, and payload.

Unsubscribing from all channels

Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken and thus, there could be some gaps in the subscription that may lead to message loss.

Method(s)

To Subscribe to a channel you can use the following method(s) in the Swift SDK:

subscribe(
to channels: [String],
and channelGroups: [String] = [],
at timetoken: Timetoken? = nil,
withPresence: Bool = false,
filterOverride: String? = nil
)
ParameterTypeRequiredDefaultDescription
to[String]YesAn array of channels to subscribe to.
and[String]Optional[]An array of channel groups to subscribe to.
atTimetoken?OptionalnilThe timetoken integer to start the subscription from.
withPresenceBoolOptionalfalseIf true it also subscribes to presence events on the specified channels.
filterOverrideString?OptionalnilOverrides the previous filter on the next successful request

Basic Usage

Subscribe to a channel:

pubnub.subscribe(to: ["my_channel"])
Event listeners

The response of the call is handled by adding a Listener. Please see the Listeners section for more details. Listeners should be added before calling the method.

Other Examples

Subscribing to multiple channels

It's possible to subscribe to more than one channel using the Multiplexing feature. The example shows how to do that using an array to specify the channel names.

Alternative subscription methods

You can also use Wildcard Subscribe and Channel Groups to subscribe to multiple channels at a time. To use these features, the Stream Controller add-on must be enabled on your keyset in the Admin Portal.

pubnub.subscribe(
to: ["my_channel", "my_channel-2", "my_channel-3"]
)
Subscribing to a Presence channel
Requires Presence add-on

This method requires that the Presence add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres to the channel name. For example the channel named my_channel would have the presence channel named my_channel-pnpres.

pubnub.subscribe(
to: ["my_channel"],
withPresence: true
)
Wildcard subscribe to channels
Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal (with Enable Wildcard Subscribe checked). Read the support page on enabling add-on features on your keys.

Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. For example, if you subscribe to a.* you will get all messages for a.b, a.c, a.x. The wildcarded * portion refers to any portion of the channel string name after the dot (.).

pubnub.subscribe(to: ["a.b.*"])
Wildcard grants and revokes

Only one level (a.*) of wildcarding is supported. If you grant on * or a.b.*, the grant will treat * or a.b.* as a single channel named either * or a.b.*. You can also revoke permissions from multiple channels using wildcards but only if you previously granted permissions using the same wildcards. Wildcard revokes, similarly to grants, only work one level deep, like a.*.

Subscribe to a channel group
Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

pubnub.subscribe(
to: [],
and: ["my_group"]
)
Subscribe to the presence channel of a channel group
note
Requires Stream Controller and Presence add-ons

This method requires both the Stream Controller and Presence add-ons are enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

pubnub.subscribe(
to: [],
and: ["my_group"],
withPresence: true
)
Subscribing to multiple channel groups
Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

pubnub.subscribe(
to: [],
and: ["my_group", "my_group-2", "my_group-3"]
)
Subscribing to a channel and channel group simultaneously
Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

pubnub.subscribe(
to: ["my_channel"],
and: ["my_group"]
)

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
}
}

Unsubscribe (deprecated)

Deprecated

This method is deprecated. Use Unsubscribe instead.

When subscribed to a single channel, this function causes the client to issue a leave from the channel and close any open socket to the PubNub Network. For multiplexed channels, the specified channel(s) will be removed and the socket remains open until there are no more channels remaining in the list.

Unsubscribing from all channels

Unsubscribing from all channels, and then subscribing to a new channel Y is not the same as subscribing to channel Y and then unsubscribing from the previously-subscribed channel(s). Unsubscribing from all channels resets the last-received timetoken and thus, there could be some gaps in the subscription that may lead to message loss.

Method(s)

To Unsubscribe from a channel you can use the following method(s) in the Swift SDK:

unsubscribe(from channels: [String], and channelGroups: [String] = [])
ParameterTypeRequiredDefaultDescription
fromArrayYesThe list of channels to unsubscribe from.
andArrayOptional[]The list of channel groups to unsubscribe from.
presenceOnlyBoolOptionalfalseIf true it only unsubscribes from presence events on the specified channels.

Basic Usage

Unsubscribe from a channel:

pubnub.unsubscribe(from: ["my_channel"])

Other Examples

Unsubscribing from multiple channels
Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

pubnub.unsubscribe(from: ["my_channel", "my_channel-2", "my_channel-3"])
Unsubscribing from multiple channel groups
Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

pubnub.unsubscribe(
from: [],
and: ["my_channel", "my_channel-2", "my_channel-3"]
)

Unsubscribe All (deprecated)

Deprecated

This method is deprecated. Use Unubscribe all instead.

Unsubscribe from all channels and all channel groups

Method(s)

unsubscribeAll()

Basic Usage

pubnub.unsubscribeAll()

Returns

None

Last updated on