Publish/Subscribe API for Swift Native SDK
PubNub delivers messages worldwide in less than 30 ms. Send a message to one recipient or broadcast to thousands of subscribers.
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. PubNub replicates the message across its points of presence and delivers it to all subscribed clients on that channel. All publish calls are performed asynchronously.
- Prerequisites and limitations
- Security
- Message data
- Size
- Publish rate
- Custom message type
- Best practices
- 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.
Secure messages with Transport Layer Security (TLS) or Secure Sockets Layer (SSL) by setting ssl
to true
during initialization. You can also encrypt messages.
The message
and meta
arguments can contain any Swift type conforming to JSONCodable
. Strings can include any UTF‑8 characters.
Don't JSON serialize
You should not JSON serialize the message
and meta
parameters when sending signals, messages, or files as the serialization is automatic. Pass the full object as the message/meta payload and let PubNub handle everything.
The maximum message size is 32 KiB. This includes the escaped character count and the channel name. Aim for under 1,800 bytes for optimal performance.
If your message exceeds the limit, you'll receive a Message Too Large
error. To learn more or calculate payload size, see Message size limits.
You can publish as fast as bandwidth allows. There is a soft throughput limit because messages may drop if subscribers can't keep up.
For example, publishing 200 messages at once may cause the first 100 to drop if a subscriber hasn't received any yet. The in-memory queue stores only 100 messages.
You can optionally provide the customMessageType
parameter to add your business-specific label or category to the message, for example text
, action
, or poll
.
- Publish to a channel serially (not concurrently).
- Verify a success return code (for example, check
Result.success
). - Publish the next message only after a success return code.
- On failure, retry.
- Keep the in-memory queue under 100 messages to avoid drops.
- Throttle bursts to meet latency needs (for example, no more than 5 messages per second).
Method(s)
To Publish a message
you can use the following method(s) in the Swift SDK:
func publish(
channel: String,
message: JSONCodable,
customMessageType: String? = nil,
shouldStore: Bool? = nil,
storeTTL: Int? = nil,
meta: AnyJSON? = nil,
shouldCompress: Bool = false,
custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
completion: ((Result<Timetoken, Error>) -> Void)?
)
Parameter | Description |
---|---|
channel *Type: String Default: n/a | The channel ID to publish to. |
message *Type: JSONCodable Default: n/a | The message to publish. |
customMessageType Type: String? Default: nil | A 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 . |
shouldStore Type: Bool? Default: nil | If true the published message is stored in history. |
storeTTL Type: Int? Default: nil | Set 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. |
meta Type: JSONCodable? Default: nil | Publish extra meta with the request. |
shouldCompress Type: Bool Default: false | When 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. |
custom Default: PubNub.RequestConfiguration() | An object that allows for per-request customization of PubNub configuration or network session. For more information, refer to the Request configuration section. |
completion Type: ((Result<Timetoken, Error>) -> Void)? Default: nil | The async Result of the method call. |
Completion handler result
Success
The Timetoken
of the published Message.
Failure
An Error
describing the failure.
Sample code
Publish a message to a channel
Reference code
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 the above dictionary as a custom Swift Object
Mix and match types with custom objects
Publish an APNs2 push notification
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 sends a message to Functions event handlers and Illuminate. The message goes directly to handlers registered on the target channel and triggers their execution. The handler can read the request body. Messages sent via fire()
aren't replicated to subscribers and aren't stored in history.
Method(s)
To Fire a message
you can use the following method(s) in the Swift SDK:
func fire(
channel: String,
message: JSONCodable,
meta: JSONCodable? = nil,
custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
completion: ((Result<Timetoken, Error>) -> Void)?
)
Parameter | Description |
---|---|
channel *Type: String Default: n/a | The channel ID to fire to. |
message *Type: JSONCodable Default: n/a | The message to fire. |
meta Type: JSONCodable? Default: nil | Publish extra meta with the request. |
custom Default: PubNub.RequestConfiguration() | An object that allows for per-request customization of PubNub configuration or network session. For more information, refer to the Request configuration section. |
completion Type: ((Result<Timetoken, Error>) -> Void)? Default: nil | The async Result of the method call. |
Completion handler result
Success
The Timetoken
of the published Message.
Failure
An Error
describing the failure.
Sample code
Fire a message to a channel
Signal
The signal()
function sends 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:
func signal(
channel: String,
message: JSONCodable,
customMessageType: String? = nil,
custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
completion: ((Result<Timetoken, Error>) -> Void)?
)
Parameter | Description |
---|---|
channel *Type: String Default: n/a | The channel ID to send a signal to. |
message *Type: JSONCodable Default: n/a | The message to signal. |
customMessageType Type: String? Default: nil | A 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 . |
custom Default: PubNub.RequestConfiguration() | An object that allows for per-request customization of PubNub configuration or network session. For more information, refer to the Request configuration section. |
completion Type: ((Result<Timetoken, Error>) -> Void)? Default: nil | The async Result of the method call. |
Completion handler result
Success
The Timetoken
of the published Message.
Failure
An Error
describing the failure.
Sample code
Signal a message to a channel
Subscribe
Subscribe opens a TCP socket and listens for messages and events on a specified entity or set of entities. Set subscribeKey
during initialization.
Conceptual overview
For more general information about subscriptions, refer to Subscriptions.
Entities are first-class citizens that expose their APIs. You can subscribe using the PubNub client or directly on a specific entity:
ChannelRepresentation
ChannelGroupRepresentation
UserMetadataRepresentation
ChannelMetadataRepresentation
After subscribe()
, the client receives new messages. Configure automaticRetry
to reconnect and fetch available messages after a disconnect.
Subscription scope
Subscriptions let you attach listeners for specific real-time update types. Your app receives messages and events through those listeners. There are two types:
Subscription
: created from an entity and scoped to that entity (for example, a particular channel)SubscriptionSet
: created from the PubNub client and scoped to the client (for example, all subscriptions created on a singlepubnub
object). A set can include one or more subscriptions.
One event listener receives all messages, signals, and events for the entities you subscribe to. To add listeners, see 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 Subscription
s 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.
To create a subscription object, call the following method on any entity defined in the Entities section:
// Entity-based, local-scoped
func subscription(
queue: DispatchQueue = .main,
options: SubscriptionOptions = SubscriptionOptions.empty()
)
Parameter | Description |
---|---|
options Type: SubscriptionOptions | Subscription 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.
To create a SubscriptionSet
, call the following method on a PubNub
instance:
// Client-based, general-scoped
func subscription(
queue: DispatchQueue = .main,
entities: any Collection<Subscribable>,
options: SubscriptionOptions = SubscriptionOptions.empty()
) -> SubscriptionSet
Parameter | Description |
---|---|
queue Type: DispatchQueue | An underlying queue to dispatch events. Defaults to the main queue. |
entities *Type: Collection<Subscribable> | One or more entities to create a subscription of. Available values include: ChannelRepresentation , ChannelGroupRepresentation , UserMetadataRepresentation , ChannelMetadataRepresentation . |
options Type: SubscriptionOptions | Subscription 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 the base class for all possible options. Available subclasses are:
Option | Description |
---|---|
ReceivePresenceEvents | Whether presence updates for userId s should be delivered through the listener streams. For information on how to receive presence events and what those events are, refer to Presence Events. |
Method(s)
Subscription
and SubscriptionSet
use the same subscribe()
method.
Subscribe
To subscribe, you can use the following method in the Swift SDK:
func subscribe(with: Timetoken? = nil)
Parameter | Description |
---|---|
with Type: Timetoken | Timetoken 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. |
Sample code
Other examples
Create a subscription set from 2 individual subscriptions
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).
ChannelRepresentation
ChannelGroupRepresentation
UserMetadataRepresentation
ChannelMetadataRepresentation
The following methods can be called on a PubNub
instance to create a local entity:
Create channels
This method returns a local ChannelRepresentation
entity.
func channel(_ name: String) -> ChannelRepresentation
Parameter | Description |
---|---|
channel *Type: String | The ID of the channel to create a subscription of. |
Sample code
Create a channel group
This method returns a local ChannelGroupRepresentation
entity.
func channelGroup(_ name: String) -> ChannelGroupRepresentation
Parameter | Description |
---|---|
name *Type: String | The name of the channel group to create a subscription of. |
Sample code
Create channel metadata
This method returns a local ChannelMetadataRepresentation
entity.
func channelMetadata(_ name: String) -> ChannelMetadataRepresentation
Parameter | Description |
---|---|
name *Type: String | The String identifier of the channel metadata object to create a subscription of. |
Sample code
Create user metadata
This method returns a local UserMetadataRepresentation
entity.
func userMetadata(_ name: String) -> UserMetadataRepresentation
Parameter | Description |
---|---|
name *Type: String | The String identifier of the user metadata object to create a subscription of. |
Sample code
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 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)
var onConnectionStateChange: ((ConnectionStatus) -> Void)?
Sample code
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 closures of real-time event listeners.
Method(s)
// Method in the `Subscription` class
func clone() -> Subscription
// Method in the `SubscriptionSet` class
func clone() -> SubscriptionSet
Sample code
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)
func unsubscribe()
Sample code
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)
func unsubscribeAll()
Sample code
Returns
None
Subscribe (old)
Not recommended
The use of this method is discouraged. 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
ID. To subscribe to a channel
ID 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.
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:
func subscribe(
to channels: [String],
and channelGroups: [String] = [],
at timetoken: Timetoken? = nil,
withPresence: Bool = false
)
Parameter | Description |
---|---|
to *Type: [String] Default: n/a | An array of channels to subscribe to. |
and Type: [String] Default: [] | An array of channel groups to subscribe to. |
at Type: Timetoken? Default: nil | The timetoken integer to start the subscription from. |
withPresence Type: Bool Default: false | If true it also subscribes to presence events on the specified channels. |
filterOverride Type: String? Default: nil | Overrides the previous filter on the next successful request |
Sample code
Subscribe to a 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.
Subscribing to a Presence channel
Requires Presence
This method requires that the Presence add-on is enabled for your key in the Admin Portal.
For information on how to receive presence events and what those events are, refer to Presence Events.
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
.
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 (.)
.
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.
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.
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.
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.
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
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
.
Case | Type | Standalone Listener | Description |
---|---|---|---|
messageReceived | PubNubMessage | didReceiveMessage | Messages sent to subscribed channels/groups |
signalReceived | PubNubMessage | didReceiveSignal | Signals sent to subscribed channels/groups |
connectionStatusChanged | ConnectionStatus | didReceiveStatus | Changes in the connection to the PubNub system |
subscriptionChanged | SubscriptionChangeEvent | didReceiveSubscriptionChange | Notifies when channels/groups are subscribed or unsubscribed |
presenceChanged | PubNubPresenceChange | didReceivePresence | Presence changes on subscribed channels/groups tracking presence |
uuidMetadataSet | PubNubUUIDMetadataChangeset | didReceiveObjectMetadataEvent | UUID metadata was set |
uuidMetadataRemoved | String | didReceiveObjectMetadataEvent | UUID metadata was removed |
channelMetadataSet | PubNubChannelMetadataChangeset | didReceiveObjectMetadataEvent | Channel metadata was set |
channelMetadataRemoved | String | didReceiveObjectMetadataEvent | Channel metadata was removed |
membershipMetadataSet | PubNubMembershipMetadata | didReceiveObjectMetadataEvent | Membership metadata was set |
membershipMetadataRemoved | PubNubMembershipMetadata | didReceiveObjectMetadataEvent | Membership metadata was removed |
messageActionAdded | PubNubMessageAction | didReceiveMessageAction | A PubNubMessageAction was added to a published message |
messageActionRemoved | PubNubMessageAction | didReceiveMessageAction | A PubNubMessageAction was removed from a published message |
subscribeError | PubNubError | subscribeError | Any error that might have occurred during the subscription stream |
Sample code
This is an example using didReceiveBatchSubscription
to allow you to receive multiple events per event call.
Other examples
For didReceiveSubscription
, simply rename the remove the for...in
loop while keeping the event switch
:
Unsubscribe (old)
Not recommended
The use of this method is discouraged. 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:
func unsubscribe(from channels: [String], and channelGroups: [String] = [])
Parameter | Description |
---|---|
from *Type: Array Default: n/a | The list of channels to unsubscribe from. |
and Type: Array Default: [] | The list of channel groups to unsubscribe from. |
presenceOnly Type: Bool Default: false | If true it only unsubscribes from presence events on the specified channels. |
Sample code
Unsubscribe from a 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.
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.
Unsubscribe all (old)
Deprecated
This method is deprecated. Use Unubscribe all instead.
Unsubscribe from all channels and all channel groups
Method(s)
func unsubscribeAll()
Sample code
Returns
None