SwiftSwift Native Publish & Subscribe API Reference for Realtime Apps

 
These docs are for the new PubNub Swift SDK written purely in Swift. To view the docs for the Older version (the PubNub Objective-C SDK wrapper for Swift), have a look here.

The publish() function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid publishKey at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.

By default, messages in transit are secured from potential eavesdroppers with SSL/TLS via the useSecureConnections configuration.

Publish Anytime

It is not required to be subscribed to a channel in order to publish to that channel.

Message Data:

The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. Message 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.

 
Do Not JSON serialize!
It is important to note that you should not JSON serialize when sending signals/messages via PUBNUB. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.
Message Size:

The maximum number of characters per message is 32K by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5KB) providing optimal network performance.

If the message you publish exceeds the configured size, you will receive the following message:

Message Too Large Error
error.pubNubError == .messageTooLong

For further details please check: https://support.pubnub.com/support/discussions/topics/14000006322

Message Publish Rate:

Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber cannot keep pace with the publisher.

For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.

Publishing to Multiple Channels:

It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.

Publishing Messages Reliably:

There are some best practices to ensure messages are delivered when publishing to a channel:

  • Publish to any given channel in a serial manner (i.e. not concurrently).
  • Ensure that the completion handler does not return an error.
  • Publish the next message only after receiving a success return code.
  • If an error is returned, 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 in accordance with your app's latency needs e.g. Publish no faster than 5 msgs per second to any one channel.
 

Single string messages are automatically sent to APNS if mobile push is enabled and devices are registered for push on that channel. So if you use encryption (cipher key in the init) and publish the message, then it will be sent to APNS if there is a device(s) registered to that channel.

This is a legacy feature and will be deprecated soon.

To Publish a message you can use the following method(s) in the Swift SDK:
  1. ParameterTypeRequiredDefaultsDescription
    channelStringYesThe channel to publish to.
    messageJSONCodableYesThe message to publish.
    shouldStoreBool?OptionalnilIf true the published message is stored in history.
    storeTTLInt?Optionalnil

    Set a per message time to live in storage.

    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 is not stored and the storeTTL parameter is ignored.
    4. If storeTTL is not specified, then expiration of the message defaults back to the expiry value for the key. """
    metaJSONCodable?OptionalnilPublish extra meta with the request.
    shouldCompressBoolOptionalfalseWhen 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.

Publish a message to a channel:

pubnub.publish(
  channel: "my-channel",
  message: "Hello from PubNub Swift SDK"
) { result in
  switch result {
    case let .success(response):
      print("Successful Response: \(response)")
    case let .failure(error):
      print("Failed Response: \(error.localizedDescription)")
  }
}
 
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.

A result of type Result<PublishResponsePayload, Error> is returned by client when publish API is used:

public struct PublishResponsePayload: Codable, Hashable {
  public let timetoken: Timetoken
}
  1. /*
    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(response):
        print("Successful Publish Response: \(response)")
      case let .failure(error):
        print("Failed Publish Response: \(error.localizedDescription)")
      }
    }
  2. // 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 {
      case let .success(response):
        print("Successful Publish Response: \(response)")
      case let .failure(error):
        print("Failed Publish Response: \(error.localizedDescription)")
      }
    }
  3. 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": {
        "lat": 37.782486,
        "long": -122.395344
      }
    }
    */
    let message = Message(greeting: "hello", location: Location(lat: 37.782486, long: -122.395344))
    
    pubnub.publish(channel: "my_channel", message: message) { result in
      switch result {
      case let .success(response):
        print("Successful Publish Response: \(response)")
      case let .failure(error):
        print("Failed Publish Response: \(error.localizedDescription)")
      }
    }
  4. 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"
    )
    
    pubnub.publish(
      channel: "my-channel",
      message: pushMessage
    ) { result in
      switch result {
        case let .success(response):
          print("Successful Response: \(response)")
        case let .failure(error):
          print("Failed Response: \(error.localizedDescription)")
      }
    }
    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?
      
      /// The payload delivered via Microsoft Push Notification Service (MPNS)
      public let mpns: JSONCodable?
      
      /// 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?
    }
The fire endpoint allows the client to send a message to PubNub Functions Event Handlers. 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() is not replicated, and so will not be received by any subscribers to the channel. The message is also not stored in history.
To Fire a message you can use the following method(s) in the Swift SDK:
  1. ParameterTypeRequiredDefaultsDescription
    channelStringYesThe channel to fire to.
    messageJSONCodableYesThe message to fire.
    metaJSONCodable?OptionalnilPublish extra meta with the request.

Fire a message to a channel:

pubnub.fire(
  channel: "my-channel",
  message: "Hello from PubNub Swift SDK"
) { result in
  switch result {
  case let .success(response):
    print("Successful Response: \(response)")
  case let .failure(error):
    print("Failed Response: \(error.localizedDescription)")
  }
}

A result of type Result<PublishResponsePayload, Error> is returned by client when publish API is used:

public struct PublishResponsePayload: Codable, Hashable {
  public let timetoken: Timetoken
}

The signal() function is used to send a signal to all subscribers of a channel.

By default, signals are limited to a message payload size of 30 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.

To Signal a message you can use the following method(s) in the Swift SDK:
  1. ParameterTypeRequiredDescription
    channelStringYesThe channel to send a signal to.
    messageJSONCodableYesThe message to signal.

Signal a message to a channel:

pubnub.signal(
  channel: "my-channel",
  message: "Hello from PubNub Swift SDK"
) { result in
  switch result {
  case let .success(response):
    print("Successful Response: \(response)")
  case let .failure(error):
    print("Failed Response: \(error.localizedDescription)")
  }
}

A result of type Result<PublishResponsePayload, Error> is returned by client when publish API is used:

public struct PublishResponsePayload: Codable, Hashable {
  public let timetoken: Timetoken
}
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. To subscribe to a channel 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.
 
You can be notified of connectivity via the connect callback. By waiting for the connect callback to return before attempting to publish, you can avoid a potential race condition on clients that subscribe and immediately publish messages before the subscribe has completed.
Using Swift SDK, if a client becomes disconnected from a channel, it can automatically attempt to reconnect to that channel and retrieve any available messages that were missed during that period by setting restore to true. By default a client will attempt to reconnect after exceeding a 320 second connection timeout.
 Unsubscribing from all the channel(s) 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 the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Subscribe to a channel you can use the following method(s) in the Swift SDK:
  1. ParameterTypeRequiredDefaultsDescription
    toArrayYesAn array of channels to subscribe to.
    andArrayOptional[] Empty ArrayAn array of channel groups to subscribe to.
    atTimetokenOptional0The timetoken integer to start the subscription from.
    withPresenceBoolOptionalfalseIf true it also subscribes to presence events on the specified channels.
    setting[String: [String: JSONCodable]]Optional[:]The object containing the state for the channel(s).
Subscribe to a channel:
pubnub.subscribe(to: ["my_channel"])
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.
  1. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    It is possible to subscribe to more than one channel over a single TCP socket by taking advantage of Multiplexing feature. See the Multiplexing section for more info on this feature as well as the examples below using a list or an array to specify channel name.
    pubnub.subscribe(
      to: [
        "my_channel",
        "my_channel-2",
        "my_channel-3"
      ]
    )
  2. Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    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.
    pubnub.subscribe(
      to: ["my_channel"],
      withPresence: true
    )
  3. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled with Enable Wildcard Subscribe checked for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. E.g., 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 (.).
     
    3 levels (2 dots) of wildcarding is supported, e.g.:
    a.*
    a.b.*
    pubnub.subscribe(to: ["a.b.*"])
  4. Requires Presence add-on XRequires that the Presence add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
     Always set the UUID to uniquely identify the user or device that connects to PubNub. This UUID should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
    pubnub.subscribe(
      to: ["my_channel"],
      setting: ["my_channel": ["some": "state"]]
    )
  5. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.subscribe(
      to: [], 
      and: ["my_group"]
    )
  6. Requires Stream Controller and Presence add-on XRequires that both Stream Controller and Presence add-ons are enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.subscribe(
      to: [],
      and: ["my_group"],
      withPresence: true
    )
  7. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.subscribe(
      to: [],
      and: ["my_group", "my_group-2", "my_group-3"]
    )
  8. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.subscribe(
      to: ["my_channel"],
      and: ["my_group"]
    )
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 the channel(s) 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 the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Unsubscribe from a channel you can use the following method(s) in the Swift SDK:
  1. ParameterTypeRequiredDefaultsDescription
    fromArrayYesThe list of channels to unsubscribe from.
    andArrayOptional[] Empty ArrayThe list of channel groups to unsubscribe from.
    presenceOnlyBoolOptionalfalseIf true it only unsubscribes from presence events on the specified channels.
Unsubscribe from a channel:
pubnub.unsubscribe(from: ["my_channel"])
  1. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.unsubscribe(from: ["my_channel", "my_channel-2", "my_channel-3"])
  2. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

    http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys.
    pubnub.unsubscribe(
      from: [], 
      and: ["my_channel", "my_channel-2", "my_channel-3"]
    )
    
Unsubscribe from all channels and all channel groups
pubnub.unsubscribeAll()
None

You can be notified of connectivity status, message and presence notifications via the listeners.

Listeners should be added before calling the method.

// Create a new listener instance
let listener = SubscriptionListener()

// Add listener event callbacks
listener.didReceiveSubscription = { event in
  switch event {
  case messageReceived(message):
    print("Message Received: \(message)")
  case connectionStatusChanged(status):
    print("Status Received: \(status)")
  case presenceChanged(event):
    print("Presence Received: \(presence)")
  case subscribeError(PubNubError):
    print("Subscription Error \(error.localizedError)")
   default:
    break
  }
}

// Start receiving subscription events
pubnub.add(listener)

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.

This is the list of event case types that can be emitted from didReceiveSubscription. Each event case also has a standalone listener that can save code space, but will be functionally equivalent to using didReceiveSubscription.

Event CaseEvent TypeStandalone ListenerEvent Description
messageReceivedMessageEventdidReceiveMessageMessages sent to subscribed channels/groups
signalReceivedMessageEventdidReceiveSignalSignals sent to subscribed channels/groups
connectionStatusChangedConnectionStatusdidReceiveStatusChanges in the connection to the PubNub system
subscriptionChangedSubscriptionChangeEventdidReceiveSubscriptionChangeNotifies when channels/groups are subscribed or unsubscribed
presenceChangedPresenceEventdidReceivePresencePresence changes on subscribed channels/groups tracking presence
userUpdatedUserEventdidReceiveUserEventA subscribed User was updated
userDeletedIdentifierEventdidReceiveUserEventA subscribed User was deleted
spaceUpdatedSpaceEvendidReceiveSpaceEventA subscribed Space was updated
spaceDeletedIdentifierEventdidReceiveSpaceEventA subscribed Space was deleted
membershipAddedMembershipEventdidReceiveMembershipEventA new membership was created
membershipUpdatedMembershipEventdidReceiveMembershipEventAn existing membership was updated
membershipDeletedMembershipIdentifiabledidReceiveMembershipEventAn existing membership was deleted
subscribeErrorPubNubErrorsubscribeErrorAny error that might have occurred during the subscription stream
messageActionAddedMessageActionEventdidReceiveMessageActionA MessageAction was added to a published message
messageActionRemovedMessageActionEventdidReceiveMessageActionA MessageAction was removed from a published message