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