Publish/Subscribe API for Swift Native SDK
The foundation of the PubNub service is the ability to send a message and have it delivered anywhere in less than 30ms. 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.
- 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.
You can secure the messages with SSL/TLS by setting ssl
to true
during initialization. You can also encrypt messages.
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
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, including the final escaped character count and the channel name. An optimal message size is under 1800 bytes.
If the message you publish exceeds the configured size, you receive a Message Too Large
error. If you want to learn more or calculate your payload size, refer to Message Size Limit.
You can publish as fast as bandwidth conditions 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, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
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 any given channel in a serial manner (not concurrently).
- Check that the return code is success (for example,
[1,"Sent","136074940..."]
) - Publish the next message only after receiving a success return code.
- If a failure code is returned (
[0,"blah","<timetoken>"]
), 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 according to your app's 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:
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)?
)
Parameter | Description |
---|---|
channel *Type: String Default: n/a | The channel to publish to. |
message *Type: JSONCodable Default: n/a | The message to publish. |
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. |
customMessageType Type: String Default: n/a | 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 Type: RequestConfiguration Default: RequestConfiguration() | An object that allows for per-request customization of PubNub Configuration or Network Session |
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.
Basic Usage
Publish a message to a channel
Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
import PubNubSDK
// Creates a configuration object using the demo keys
let config = PubNubConfiguration(
publishKey: "demo",
subscribeKey: "demo",
userId: "myUniqueUserId"
)
// Initializes a PubNub object with the configuration
let pubnub = PubNub(configuration: config)
// Publish a message to a channel
func publishExample() {
pubnub.publish(
show all 27 linesSubscribe 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 linesPublish 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 linesMix 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 linesPublish 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 linesRoot 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)?
)
Parameter | Description |
---|---|
channel *Type: String Default: n/a | The channel 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 Type: RequestConfiguration Default: RequestConfiguration() | An object that allows for per-request customization of PubNub Configuration or Network Session |
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.