Publish/Subscribe API for Swift Native SDK
PubNub's publish-processing latency, the time to accept and acknowledge a publish request, is about 0.5 ms within the same region. 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.
#
- 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, see Message size limits. To calculate payload size, use the message size calculator.
Need larger messages?
PubNub supports payloads larger than the standard limit, but raising it requires verifying compatibility with your use case.
Talk to our team to discuss increasing the message size limit for your use case.
#
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:
1func publish(
2 channel: String,
3 message: JSONCodable,
4 customMessageType: String? = nil,
5 shouldStore: Bool? = nil,
6 storeTTL: Int? = nil,
7 meta: AnyJSON? = nil,
8 shouldCompress: Bool = false,
9 custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
10 completion: ((Result<Timetoken, Error>) -> Void)?
11)
channelrequired#- The
channelID to publish to. messagerequired#- The
messageto publish. customMessageType#- 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 stringpn_orpn-.
Examples:text,action,poll. shouldStore#- If
truethe published message is stored in history. storeTTL#- Set a per message time to live in Message Persistence. 1. If shouldStore =
true, andstoreTTL= 0, the message is stored with no expiry time. 2. If shouldStore =trueandstoreTTL= X (X is an Integer value), the message is stored with an expiry time of X hours. 3. If shouldStore isfalseor not specified, the message isn't stored and thestoreTTLparameter is ignored. 4. IfstoreTTLisn't specified, then expiration of the message defaults back to the expiry value for the key. meta#- Publish extra
metawith the request. shouldCompress#- 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#- An object that allows for per-request customization of PubNub configuration or network session. For more information, refer to the Request configuration section.
completion#- The async
Resultof 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
1import PubNubSDK
2
3// Initializes a PubNub object with the configuration
4let pubnub = PubNub(
5 configuration: PubNubConfiguration(
6 publishKey: "demo",
7 subscribeKey: "demo",
8 userId: "myUniqueUserId"
9 )
10)
11
12// Publish a message to a channel
13pubnub.publish(
14 channel: "my-channel",
15 message: "Hello from PubNub Swift SDK",
show all 24 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
1/// Publish payload JSON equivalent to:
2///
3/// ```
4/// {
5/// "greeting": "hello",
6/// "location": "right here"
7/// }
8/// ```
9pubnub.publish(
10 channel: "my_channel",
11 message: ["greeting": "hello", "location": "right here"]
12) { result in
13 switch result {
14 case let .success(timetoken):
15 print("Message Successfully Published at: \(timetoken)")
show all 19 linesPublish the above dictionary as a custom Swift Object
1/// Ensure that your custom type implements `JSONCodable`
2struct Message: JSONCodable {
3 var greeting: String
4 var location: String
5}
6
7/// Publish payload JSON equivalent to:
8///
9/// ```
10/// {
11/// "greeting": "hello",
12/// "location": "right here"
13/// }
14/// ```
15pubnub.publish(
show all 25 linesMix and match types with custom objects
1/// Ensure that your custom type implements `JSONCodable`
2struct CustomMessage: JSONCodable {
3 var greeting: String
4 var location: Location
5}
6
7/// Ensure that your custom type implements `JSONCodable`
8struct Location: JSONCodable {
9 var lat: Double
10 var long: Double
11}
12
13/// Publish payload JSON equivalent to:
14///
15/// ```
show all 34 linesPublish an APNs2 push notification
1// Publish a message to a channel with APNS and FCM payloads
2let pushMessage = PubNubPushMessage(
3 apns: PubNubAPNSPayload(
4 aps: APSPayload(alert: .object(.init(title: "Apple Message")), badge: 1, sound: .string("default")),
5 pubnub: [.init(
6 targets: [.init(topic: "com.pubnub.swift", environment: .production)],
7 collapseID: "SwiftSDK",
8 pushType: .alert
9 )],
10 payload: "Push Message from PubNub Swift SDK"
11 ),
12 fcm: PubNubFCMPayload(
13 payload: "Push Message from PubNub Swift SDK",
14 target: .topic("com.pubnub.swift"),
15 notification: FCMNotificationPayload(title: "Android Message"),
show all 31 linesRoot level push message object
1public struct PubNubPushMessage: JSONCodable {
2
3 /// The payload delivered via Apple Push Notification service (APNS)
4 public let apns: PubNubAPNSPayload?
5
6 /// The payload delivered via Firebase Cloud Messaging service (FCM)
7 public let fcm: PubNubFCMPayload?
8
9 /// Additional message payload sent outside of the push notification
10 ///
11 /// In order to guarantee valid JSON any scalar values will be assigned to the `data` key.
12 /// Non-scalar values will retain their coding keys.
13 public var additionalMessage: JSONCodable?
14}
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:
1func fire(
2 channel: String,
3 message: JSONCodable,
4 meta: JSONCodable? = nil,
5 custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
6 completion: ((Result<Timetoken, Error>) -> Void)?
7)
channelrequired#- The
channelID to fire to. messagerequired#- The
messageto fire. meta#- Publish extra
metawith the request. custom#- An object that allows for per-request customization of PubNub configuration or network session. For more information, refer to the Request configuration section.
completion#- The async
Resultof 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
1// Publish a message to PubNub Functions Event Handlers
2pubnub.fire(
3 channel: "my-channel",
4 message: "Hello from PubNub Swift SDK"
5) { result in
6 switch result {
7 case let .success(timetoken):
8 print("Message Successfully Published at: \(timetoken)")
9 case let .failure(error):
10 print("Failed Response: \(error.localizedDescription)")
11 }
12}
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:
1func signal(
2 channel: String,
3 message: JSONCodable,
4 customMessageType: String? = nil,
5 custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
6 completion: ((Result<Timetoken, Error>) -> Void)?
7)
channelrequired#- The channel ID to send a signal to.
messagerequired#- The message to signal.
customMessageType#- 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 stringpn_orpn-.
Examples:text,action,poll. custom#- An object that allows for per-request customization of PubNub configuration or network session. For more information, refer to the Request configuration section.
completion#- The async
Resultof 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
1// Send a signal to a channel
2pubnub.signal(
3 channel: "my-channel",
4 message: "Hello from PubNub Swift SDK",
5 customMessageType: "text-message-signalled"
6) { result in
7 switch result {
8 case let .success(timetoken):
9 print("Message Successfully Published at: \(timetoken)")
10 case let .failure(error):
11 print("Failed Response: \(error.localizedDescription)")
12 }
13}
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:
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 singlepubnubobject). 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 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.
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()
)
options#Subscriptionbehavior 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,
targets: any Collection<Subscribable>,
options: SubscriptionOptions = SubscriptionOptions.empty()
) -> SubscriptionSet
queue#- An underlying queue to dispatch events. Defaults to the main queue.
targetsrequired#- One or more entities to create a subscription of. Available values include:
Channel,ChannelGroup,UserMetadata,ChannelMetadata,DataSyncUser,DataSyncChannel,DataSyncEntity. options#Subscriptionbehavior 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 userIds 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)
with#- 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
1import PubNubSDK
2
3// Initializes a PubNub object with the configuration
4let pubnub = PubNub(
5 configuration: PubNubConfiguration(
6 publishKey: "demo",
7 subscribeKey: "demo",
8 userId: "myUniqueUserId"
9 )
10)
11
12// Create a subscription for a Pub/Sub channel
13let subscription = pubnub.channel("channel").subscription(options: ReceivePresenceEvents())
14// Triggers the subscription
15subscription.subscribe()
Other examples
Create a subscription set from 2 individual subscriptions
1// Create a reference to a Pub/Sub channel
2let weatherChannel = pubnub.channel("weather-updates")
3// Create a reference to a Pub/Sub channel group
4let newsGroup = pubnub.channelGroup("news-feed")
5
6// Create a SubscriptionSet object from the values above
7let subscriptionSet = pubnub.subscription(targets: [weatherChannel, newsGroup])
8
9// Create a subscription for another Pub/Sub channel to demonstrate
10// adding and removing to/from a SubscriptionSet
11let sportsSubscription = pubnub.channel("sports-scores").subscription()
12
13// An example of how to add/remove a `sportsSubscription` to/from a SubscriptionSet
14subscriptionSet.add(subscription: sportsSubscription)
15subscriptionSet.remove(subscription: sportsSubscription)
show all 18 linesReturns
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).
SDK entity is not the same as a DataSync entity
An SDK entity is the local handle described in this section. A DataSync entity is a stored server-side record, managed through the DataSync API.
The following methods can be called on a PubNub instance to create a local entity:
Create channels
This method returns a local Channel entity.
func channel(_ name: String) -> Channel
Sample code
1// Create a Pub/Sub channel reference
2pubnub.channel("channelName")
Create a channel group
This method returns a local ChannelGroup entity.
func channelGroup(_ name: String) -> ChannelGroup
namerequired#- The name of the channel group to create a subscription of.
Sample code
1// Create a Pub/Sub channel group reference
2pubnub.channelGroup("channelGroupName")
Create channel metadata
This method returns a local ChannelMetadata entity.
func channelMetadata(_ name: String) -> ChannelMetadata
namerequired#- The String identifier of the channel metadata object to create a subscription of.
Sample code
1// Create an App Context channel metadata reference
2pubnub.channelMetadata("channelMetadataId")
Create user metadata
This method returns a local UserMetadata entity.
func userMetadata(_ name: String) -> UserMetadata
namerequired#- The String identifier of the user metadata object to create a subscription of.
Sample code
1// Create an App Context user metadata reference
2pubnub.userMetadata("userMetadataId")
DataSync SDK entities
DataSync SDK entities are SDK entities whose only job is to subscribe to a DataSync object's real-time updates. Like the other entities, they send no request and change nothing on the server. Call these methods on a PubNub instance to create one:
| Method | Returns | Subscribes to |
|---|---|---|
dataSyncUser(_ id: String) | DataSyncUser | A user |
dataSyncChannel(_ id: String) | DataSyncChannel | A channel |
dataSyncEntity(_ id: String) | DataSyncEntity | An entity |
idrequired#- The identifier of the DataSync object. The SDK builds the data channel name from it.
No handles for memberships and relationships
Memberships and relationships never publish on a channel named after their own id, so the SDK has no subscribable handle for them. To follow a membership, subscribe to the user or channel it links. Refer to where each event is delivered.
Call subscription() on a DataSync SDK entity to subscribe to its base projection. It takes the same queue and options as any other entity. A DataSync object has no presence channel, so the SDK ignores presence options.
1func subscription(
2 projection projectionName: String,
3 queue: DispatchQueue = .main,
4 options: SubscriptionOptions = SubscriptionOptions.empty()
5) -> Subscription
projectionrequired#- Name of a projection declared on the class. The subscription receives only the fields tagged with that projection.
queue#- An underlying queue to dispatch events. Defaults to the main queue.
options#Subscriptionbehavior configuration.
Sample code
1// Create a Data Sync user reference
2pubnub.dataSyncUser("player-1")
1// Create a Data Sync channel reference
2pubnub.dataSyncChannel("team-1")
1// Create a Data Sync custom entity reference
2pubnub.dataSyncEntity("match-1")
1// Subscribe to a custom projection of a Data Sync entity
2pubnub.dataSyncEntity("match-1").subscription(projection: "stats")
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.
No built-in event throttling
The PubNub SDK delivers every incoming event to your listener as it arrives. There is no built-in throttling or rate-limiting on the subscriber side. If you need to control how often your application processes events, wrap your listener callback with a throttle or debounce utility from your language or framework ecosystem.
To reduce the number of messages delivered to your client in the first place, use Subscribe Filters to filter messages server-side before they reach your listener.
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)
1import PubNubSDK
2
3// Initializes a PubNub object with the configuration
4let pubnub = PubNub(
5 configuration: PubNubConfiguration(
6 publishKey: "demo",
7 subscribeKey: "demo",
8 userId: "myUniqueUserId"
9 )
10)
11
12// Create a subscription for a Pub/Sub channel
13let subscription = pubnub
14 .channel("channelName")
15 .subscription()
1// Defines a custom type that can be used to decode the message payload
2struct Person: JSONCodable {
3 var lastName: String
4 var firstName: String
5 var age: Int
6}
7
8// Add a listener for Message events
9subscription.onMessage = { message in
10 // Example showing how to decode the message payload as the custom Person type defined above
11 if let person = try? message.payload.decode(Person.self) {
12 print("Person object decoded successfully")
13 print("Person details: \(person.lastName), \(person.firstName), \(person.age)")
14 }
15 // Example showing how to decode the message payload as a raw [String: Any] dictionary
show all 36 lines1// Add a listener to receive Presence events (requires a subscription with presence)
2subscription.onPresence = { presenceChange in
3 for action in presenceChange.actions {
4 switch action {
5 case let .join(uuids):
6 print("Occupants joined at \(presenceChange.timetoken): \(uuids)")
7 case let .leave(uuids):
8 print("Occupants left at \(presenceChange.timetoken): \(uuids)")
9 case let .timeout(uuids):
10 print("Occupants timed-out at \(presenceChange.timetoken): \(uuids)")
11 case let .stateChange(uuid, state):
12 print("\(uuid) changed state to \(state) at \(presenceChange.timetoken)")
13 }
14 }
15}
1// Add a listener to receive Message Action events
2subscription.onMessageAction = { messageActionEvent in
3 switch messageActionEvent {
4 case let .added(messageAction):
5 print("Message action added in \(messageAction.channel) channel at message timetoken \(messageAction.messageTimetoken)")
6 case let .removed(messageAction):
7 print("A message reaction with the timetoken of \(messageAction.actionTimetoken) has been removed")
8 }
9}
1// Add a listener to receive App Context user, channel, and membership metadata events
2subscription.onAppContext = { appContextEvent in
3 switch appContextEvent {
4 case let .userMetadataSet(changeset):
5 print("User metadata changes detected for \(changeset.metadataId) at \(changeset.updated).")
6 print("All changes made to the object: \(changeset.changes)")
7 print("To apply these changes, fetch the relevant object and call `changeset.apply(to: otherUserMetadata)`.")
8 case let .userMetadataRemoved(metadataId):
9 print("Metadata for User \(metadataId) removed")
10 case let .channelMetadataSet(changeset):
11 print("Channel metadata changes detected for \(changeset.metadataId) at \(changeset.updated).")
12 print("All changes made to the object: \(changeset.changes)")
13 print("To apply these changes, fetch the relevant object and call `changeset.apply(to: otherChannelMetadata)`.")
14 case let .channelMetadataRemoved(metadataId: metadataId):
15 print("Metadata for channel \(metadataId) removed")
show all 21 lines1// Add a listener to receive File events
2subscription.onFileEvent = { fileEvent in
3 if case let .uploaded(fileInfo) = fileEvent {
4 print("File uploaded: \(fileInfo)")
5 }
6}
1// Add a batched subscription event that possibly contains multiple events
2subscription.onEvents = { events in
3 print("Received events: \(events)")
4}
1// Add a listener to capture single event
2subscription.onEvent = { event in
3 switch event {
4 case let .messageReceived(message):
5 print("Message Received: \(message) Publisher: \(message.publisher ?? "defaultUUID")")
6 case let .signalReceived(signal):
7 print("Signal Received: \(signal)")
8 case let .presenceChanged(presence):
9 print("Presence event: \(presence)")
10 case let .appContextChanged(appContextEvent):
11 print("App Context metadata change event: \(appContextEvent)")
12 case let .messageActionChanged(messageActionEvent):
13 print("Message Reaction event: \(messageActionEvent)")
14 case let .fileChanged(fileEvent):
15 print("File event: \(fileEvent)")
show all 21 linesAdd DataSync listener
DataSync objects publish create, update, and delete events when events are enabled for their class. An update or delete is also delivered on the channel of every connected object, so a subscription can receive an event for an object that it did not subscribe to. Refer to where each event is delivered for the rules.
Assign the onDataSync closure on a Subscription, on a SubscriptionSet, or on the PubNub client, which receives DataSync events for every active subscription.
Method(s)
1var onDataSync: ((PubNubDataSyncEvent) -> Void)?
Enable events for the class
To receive DataSync events, enable event publishing for the object's class in the Admin Portal. Refer to DataSync events for details.
Projection filtering
An event published on a projection channel carries only the payload and status fields that the class declares under that projection. id, eTag, createdAt, updatedAt, and expiresAt are never filtered, and delete events are never filtered. Refer to projection channels for details.
Event object
PubNubDataSyncEvent describes one change received over subscribe.
PubNubDataSyncEvent.Change has one case per change:
| Case | Associated value | Description |
|---|---|---|
entityCreated | PubNubDataSyncEntityEvent | A user, channel, or entity was created. |
entityUpdated | PubNubDataSyncEntityEvent | A user, channel, or entity was updated. |
entityDeleted | PubNubDataSyncEntityDeletedEvent | A user, channel, or entity was deleted. |
relationshipCreated | PubNubDataSyncRelationshipEvent | A membership or relationship was created. |
relationshipUpdated | PubNubDataSyncRelationshipEvent | A membership or relationship was updated. |
relationshipDeleted | PubNubDataSyncRelationshipDeletedEvent | A membership or relationship was deleted. |
unknown | PubNubDataSyncUnknownEvent | A change this version of the SDK doesn't recognize. |
PubNubDataSyncEntityEvent carries a created or updated entity.
PubNubDataSyncEntity has these properties:
id#- The unique identifier of the entity.
className#- The name of the entity's class.
classLevel#- The level the class is registered at.
classVersion#- The version of the class.
createdAt#- When the entity was created.
updatedAt#- When the entity was last updated.
eTag#- The revision used for optimistic concurrency.
expiresAt#- When the entity expires.
status#- The free-form status. Subject to projection filtering.
payload#- The entity fields. Subject to projection filtering.
PubNubDataSyncRelationshipEvent carries a created or updated relationship.
PubNubDataSyncRelationship has the id, className, classVersion, createdAt, updatedAt, eTag, expiresAt, status, and payload properties, plus entityAId and entityBId for the two linked entities. PubNubDataSyncMembership exposes the same state as channelId and userId.
- A delete event carries
removedinstead of the full state.PubNubDataSyncRemovedEntityandPubNubDataSyncRemovedRelationshiphold theid,className,classLevel,classVersion, anddeletedAt. - For a membership event,
entityAIdis the channel id andentityBIdis the user id. The service sends them aschannelIdanduserId, and the SDK maps them onto the A and B sides. PubNubDataSyncUnknownEventcarries the rawtype,event,metadata, andpayload, so an event from a newer service version doesn't get lost.
Sample code
1import PubNubSDK
2
3// Initializes a PubNub object with the configuration
4let pubnub = PubNub(
5 configuration: PubNubConfiguration(
6 publishKey: "demo",
7 subscribeKey: "demo",
8 userId: "myUniqueUserId"
9 )
10)
11
12// Create a subscription for a custom projection of a Data Sync entity
13let dataSyncSubscription = pubnub
14 .dataSyncEntity("match-1")
15 .subscription(projection: "stats")
show all 60 linesFor the fetch methods, refer to DataSync API. For the concurrency pattern, refer to the ETags concept documentation.
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)
1var onConnectionStateChange: ((ConnectionStatus) -> Void)?
Sample code
1// Sets a callback to handle connection state changes
2pubnub.onConnectionStateChange = { newStatus in
3 print("Connection status: \(newStatus)")
4}
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)
1// Method in the `Subscription` class
2func clone() -> Subscription
3// Method in the `SubscriptionSet` class
4func clone() -> SubscriptionSet
Sample code
1// Create a subscription set containing a Pub/Sub channel and channel group
2let subscriptionSet = pubnub.subscription(
3 targets: [pubnub.channel("channel"), pubnub.channelGroup("channelGroup")],
4 options: ReceivePresenceEvents()
5)
6// Create a subscription for a Pub/Sub channel
7let subscription = pubnub
8 .channel("channelName")
9 .subscription()
10
11let clonedSubscriptionSet = subscriptionSet.clone()
12let clonedSubscription = subscription.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)
func unsubscribe()
Sample code
1subscription.unsubscribe()
2subscriptionSet.unsubscribe()
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)
1func unsubscribeAll()
Sample code
1// Unsubscribes from all channels and channel groups
2pubnub.unsubscribeAll()
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:
1func subscribe(
2 to channels: [String],
3 and channelGroups: [String] = [],
4 at timetoken: Timetoken? = nil,
5 withPresence: Bool = false
6)
torequired#- An array of channels to subscribe to.
and#- An array of channel groups to subscribe to.
at#- The timetoken integer to start the subscription from.
withPresence#- If
trueit also subscribes to presence events on the specified channels. filterOverride#- Overrides the previous filter on the next successful request
Sample code
Subscribe to a channel:
1pubnub.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.
1pubnub.subscribe(to: ["my_channel", "my_channel-2", "my_channel-3"])
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.
1pubnub.subscribe(
2 to: ["my_channel"],
3 withPresence: true
4)
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). See Enable the features your app calls.
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 (.).
1pubnub.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. See Enable the features your app calls.
1pubnub.subscribe(
2 to: [],
3 and: ["my_group"]
4)
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. See Enable the features your app calls.
1pubnub.subscribe(
2 to: [],
3 and: ["my_group"],
4 withPresence: true
5)
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. See Enable the features your app calls.
1pubnub.subscribe(
2 to: [],
3 and: ["my_group", "my_group-2", "my_group-3"]
4)
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. See Enable the features your app calls.
1pubnub.subscribe(
2 to: ["my_channel"],
3 and: ["my_group"]
4)
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
1import PubNubSDK
2
3// Initializes a PubNub object with the configuration
4let pubnub = PubNub(
5 configuration: PubNubConfiguration(
6 publishKey: "demo",
7 subscribeKey: "demo",
8 userId: "myUniqueUserId"
9 )
10)
11
12// Create a new listener instance
13let listener = SubscriptionListener()
14
15// Add listener event callbacks
show all 29 linesHow 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.
1listener.didReceiveBatchSubscription = { events in
2 for event in events {
3 switch event {
4 case .messageReceived(let message):
5 print("The \(message.channel) channel received a message at \(message.published).")
6 print("The channel group or wildcard subscription match (if exists): \(String(describing: message.subscription)).")
7 print("Message payload: \(message.payload). Sent by: \(message.publisher ?? "unknown").")
8
9 case .signalReceived(let signal):
10 print("The \(signal.channel) channel received a signal at \(signal.published).")
11 print("The channel group or wildcard subscription match (if exists): \(String(describing: signal.subscription)).")
12 print("Signal payload: \(signal.payload). Sent by: \(signal.publisher ?? "unknown").")
13
14 case .presenceChanged(let presenceChange):
15 print("Presence updated for channel \(presenceChange.channel)")
show all 111 linesOther examples
For didReceiveSubscription, simply rename the remove the for...in loop while keeping the event switch:
1listener.didReceiveSubscription = { event in
2 switch event {
3 // Same content as the above example
4 default:
5 break
6 }
7}
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:
1func unsubscribe(from channels: [String], and channelGroups: [String] = [])
Sample code
Unsubscribe from a channel:
1pubnub.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. See Enable the features your app calls.
1pubnub.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. See Enable the features your app calls.
1pubnub.unsubscribe(
2 from: [],
3 and: ["my_channel", "my_channel-2", "my_channel-3"]
4)
Unsubscribe all (old)
Deprecated
This method is deprecated. Use Unubscribe all instead.
Unsubscribe from all channels and all channel groups
Method(s)
1func unsubscribeAll()
Sample code
1pubnub.unsubscribeAll()
Returns
None