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.

#

#

#

#

#

#

#

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)
required
channel required#
Type: String
Default: no default
The channel ID to publish to.
message required#
Type: JSONCodable
Default: no default
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​

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 lines
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​

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 lines

Publish 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 lines

Mix 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 lines

Publish 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 lines

Root 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)
required
channel required#
Type: String
Default: no default
The channel ID to fire to.
message required#
Type: JSONCodable
Default: no default
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​

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)
required
channel required#
Type: String
Default: no default
The channel ID to send a signal to.
message required#
Type: JSONCodable
Default: no default
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​

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 single pubnub 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 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#
Type: SubscriptionOptions

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
required
queue#
Type: DispatchQueue
An underlying queue to dispatch events. Defaults to the main queue.
targets required#
Type: Collection<Subscribable>
One or more entities to create a subscription of. Available values include: Channel, ChannelGroup, UserMetadata, ChannelMetadata, DataSyncUser, DataSyncChannel, DataSyncEntity.
options#
Type: SubscriptionOptions
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:

OptionDescription
ReceivePresenceEventsWhether 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#
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​
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 lines
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).

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
required
channel required#
Type: String
The ID of the channel to create a subscription of.

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
required
name required#
Type: String
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
required
name required#
Type: String
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
required
name required#
Type: String
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:

MethodReturnsSubscribes to
dataSyncUser(_ id: String)DataSyncUserA user
dataSyncChannel(_ id: String)DataSyncChannelA channel
dataSyncEntity(_ id: String)DataSyncEntityAn entity
required
id required#
Type: String
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
required
projection required#
Type: String
Name of a projection declared on the class. The subscription receives only the fields tagged with that projection.
queue#
Type: DispatchQueue
An underlying queue to dispatch events. Defaults to the main queue.
options#
Type: SubscriptionOptions

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 lines
1// 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 lines
1// 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 lines

Add 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.

channel#
Type: String
The channel the event was received on.
subscription#
Type: String?
The channel group or wildcard subscription match, if any.
timetoken#
Type: Timetoken
The timetoken for when the event was published.
change#
Type: PubNubDataSyncEvent.Change
The change the event describes.

PubNubDataSyncEvent.Change has one case per change:

CaseAssociated valueDescription
entityCreatedPubNubDataSyncEntityEventA user, channel, or entity was created.
entityUpdatedPubNubDataSyncEntityEventA user, channel, or entity was updated.
entityDeletedPubNubDataSyncEntityDeletedEventA user, channel, or entity was deleted.
relationshipCreatedPubNubDataSyncRelationshipEventA membership or relationship was created.
relationshipUpdatedPubNubDataSyncRelationshipEventA membership or relationship was updated.
relationshipDeletedPubNubDataSyncRelationshipDeletedEventA membership or relationship was deleted.
unknownPubNubDataSyncUnknownEventA change this version of the SDK doesn't recognize.

PubNubDataSyncEntityEvent carries a created or updated entity.

kind#
Type: PubNubDataSyncEntityKind
The object kind, either user, channel, or custom for an entity.
entity#
Type: PubNubDataSyncEntity
The created or updated entity.
object#
Type: PubNubDataSyncEntityEvent.Object
The same state narrowed to user(PubNubDataSyncUser), channel(PubNubDataSyncChannel), or custom(PubNubDataSyncEntity).

PubNubDataSyncEntity has these properties:

id#
Type: String
The unique identifier of the entity.
className#
Type: String
The name of the entity's class.
classLevel#
Type: PubNubDataSyncClassLevel
The level the class is registered at.
classVersion#
Type: Int
The version of the class.
createdAt#
Type: Date
When the entity was created.
updatedAt#
Type: Date
When the entity was last updated.
eTag#
Type: String
The revision used for optimistic concurrency.
expiresAt#
Type: Date
When the entity expires.
status#
Type: String?
The free-form status. Subject to projection filtering.
payload#
Type: JSONCodable?
The entity fields. Subject to projection filtering.

PubNubDataSyncRelationshipEvent carries a created or updated relationship.

kind#
Type: PubNubDataSyncRelationshipKind
The object kind, either membership or custom for a relationship.
relationship#
Type: PubNubDataSyncRelationship
The created or updated relationship.
object#
Type: PubNubDataSyncRelationshipEvent.Object
The same state narrowed to membership(PubNubDataSyncMembership) or custom(PubNubDataSyncRelationship).

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 removed instead of the full state. PubNubDataSyncRemovedEntity and PubNubDataSyncRemovedRelationship hold the id, className, classLevel, classVersion, and deletedAt.
  • For a membership event, entityAId is the channel id and entityBId is the user id. The service sends them as channelId and userId, and the SDK maps them onto the A and B sides.
  • PubNubDataSyncUnknownEvent carries the raw type, event, metadata, and payload, 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 lines

For 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)
required
to required#
Type: [String]
Default: no default
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:

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 lines
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.

CaseTypeStandalone ListenerDescription
messageReceivedPubNubMessagedidReceiveMessageMessages sent to subscribed channels/groups
signalReceivedPubNubMessagedidReceiveSignalSignals sent to subscribed channels/groups
connectionStatusChangedConnectionStatusdidReceiveStatusChanges in the connection to the PubNub system
subscriptionChangedSubscriptionChangeEventdidReceiveSubscriptionChangeNotifies when channels/groups are subscribed or unsubscribed
presenceChangedPubNubPresenceChangedidReceivePresencePresence changes on subscribed channels/groups tracking presence
uuidMetadataSetPubNubUUIDMetadataChangesetdidReceiveObjectMetadataEventUUID metadata was set
uuidMetadataRemovedStringdidReceiveObjectMetadataEventUUID metadata was removed
channelMetadataSetPubNubChannelMetadataChangesetdidReceiveObjectMetadataEventChannel metadata was set
channelMetadataRemovedStringdidReceiveObjectMetadataEventChannel metadata was removed
membershipMetadataSetPubNubMembershipMetadatadidReceiveObjectMetadataEventMembership metadata was set
membershipMetadataRemovedPubNubMembershipMetadatadidReceiveObjectMetadataEventMembership metadata was removed
messageActionAddedPubNubMessageActiondidReceiveMessageActionA PubNubMessageAction was added to a published message
messageActionRemovedPubNubMessageActiondidReceiveMessageActionA PubNubMessageAction was removed from a published message
subscribeErrorPubNubErrorsubscribeErrorAny 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 lines

Other 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] = [])
required
from required#
Type: Array
Default: no default
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:

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

Was this page useful?

Last updated on