Publish/Subscribe 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.

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

Description

The publish() function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid publishKey at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.

All publish calls are performed asynchronously.

By default, messages in transit are secured from potential eavesdroppers with SSL/TLS via the useSecureConnections configuration.

Publish Anytime

It's not required to be subscribed to a channel in order to publish to that channel.

Message Data

The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. data can contain any Swift class that conforms to Codable and JSONCodable protocols. String content can include any single-byte or multi-byte UTF-8 character.

Don't JSON serialize

It is important to note that you should not JSON serialize when sending signals/messages via PUBNUB. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.

Message Size

The maximum number of characters per message is 32 KiB by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5 KiB) providing optimal network performance.

If the message you publish exceeds the configured size, you will receive the following message:

Message Too Large Error
error.pubNubError == .messageTooLong

For further details, check the support article.

Message Publish Rate

Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber can't keep pace with the publisher.

For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.

Publishing to Multiple Channels

It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.

Publishing Messages Reliably

There are some best practices to ensure messages are delivered when publishing to a channel:

  • Publish to any given channel in a serial manner (not concurrently).
  • Ensure that the completion handler doesn't return an error.
  • Publish the next message only after receiving a success return code.
  • If an error is returned, retry the publish.
  • Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
  • Throttle publish bursts in accordance with your app's latency needs, such as publishing no more than 5 messages per second to any one channel.

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,  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 storage. 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.
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"
) { 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

Description

The fire endpoint allows the client to send a message to PubNub Functions Event Handlers. 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

Description

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)
ParameterTypeRequiredDefaultDescription
channelStringYesThe channel to send a signal to.
messageJSONCodableYesThe message to signal.
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"
) { result in
switch result {
case let .success(timetoken):
print("Message Successfully Published at: \(timetoken)")
case let .failure(error):
print("Failed Response: \(error.localizedDescription)")
}
}

Subscribe

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

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"]
)

Unsubscribe

Description

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

Description

Unsubscribe from all channels and all channel groups

Method(s)

unsubscribeAll()

Basic Usage

pubnub.unsubscribeAll()

Returns

None

Last updated on