SwiftSwift Native Publish & Subscribe API Reference for Realtime Apps

 
The PubNub Swift 3.0 SDK contains many significant changes from the 2.x SDK, including breaking changes. Please refer to the PubNub Swift 3.0 Migration Guide for more details.

The foundation of the PubNub service is the ability to send a message and have it delivered anywhere in less than 100ms. Send a message to just one other person, or broadcast to thousands of subscribers at once.

For higher-level conceptual details on publishing and subscribing, refer to Connection Management and to Publish Messages.

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.

All publish calls are performed asynchronously.

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

Publish Anytime

It's 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. data can contain any Swift class that conforms to Codable and JSONCodable protocols. String content can include any single-byte or multi-byte UTF-8 character.

 
Don't JSON serialize!
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 32 KiB 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.5 KiB) 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/solutions/articles/14000113049-calculating-message-payload-size-before-publish.

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 can't keep pace with the publisher.

For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any 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 (not concurrently).
  • Ensure that the completion handler doesn't 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, such as publishing no more than 5 messages per second to any one channel.
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?OptionalnilSet 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 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.
    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.
    customRequestConfigurationOptionalRequestConfiguration()An object that allows for per-request customization of PubNub Configuration or Network Session
    completion((Result<Timetoken, Error>) -> Void)?OptionalnilThe async Result of the method call

    Completion Handler Result

    • Success: The Timetoken of the published Message
    • Failure: An Error describing the failure

Publish a message to a channel:

pubnub.publish(
  channel: "my-channel",
  message: "Hello from PubNub Swift SDK"
) { result in
  switch result {
  case let .success(timetoken):
    print("Message Successfully Published at: \(timetoken)")
  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.
  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(timetoken):
        print("Message Successfully Published at: \(timetoken)")
      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(timetoken):
        print("Message Successfully Published at: \(timetoken)")
      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(timetoken):
        print("Message Successfully Published at: \(timetoken)")
      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(timetoken):
        print("Message Successfully Published at: \(timetoken)")
      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() isn't replicated, and so won't 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.
    customRequestConfigurationOptionalRequestConfiguration()An object that allows for per-request customization of PubNub Configuration or Network Session
    completion((Result<Timetoken, Error>) -> Void)?OptionalnilThe async Result of the method call

    Completion Handler Result

    • Success: The Timetoken of the published Message
    • Failure: An Error describing the failure

Fire a message to a channel:

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

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. ParameterTypeRequiredDefaultsDescription
    channelStringYesThe channel to send a signal to.
    messageJSONCodableYesThe message to signal.
    customRequestConfigurationOptionalRequestConfiguration()An object that allows for per-request customization of PubNub Configuration or Network Session
    completion((Result<Timetoken, Error>) -> Void)?OptionalnilThe async Result of the method call

    Completion Handler Result

    • Success: The Timetoken of the published Message
    • Failure: An Error describing the failure

Signal a message to a channel:

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

The PubNub Swift SDK removes (dedupes) messages automatically if they have the same timetoken, publisher, and payload.

 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.
To Subscribe to a channel you can use the following method(s) in the Swift SDK:
  1. ParameterTypeRequiredDefaultsDescription
    to[String]YesAn array of channels to subscribe to.
    and[String]Optional[]An array of channel groups to subscribe to.
    atTimetoken?OptionalnilThe timetoken integer to start the subscription from.
    withPresenceBoolOptionalfalseIf true it also subscribes to presence events on the specified channels.
    filterOverrideString?OptionalnilOverrides the previous filter on the next successful request
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 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"]
    )
  5. 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
    )
  6. 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"]
    )
  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: ["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 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.
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[]The 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 let .messageReceived(message):
    print("Message Received: \(message) Publisher: \(message.publisher ?? "defaultUUID")")
  case let .connectionStatusChanged(status):
    print("Status Received: \(status)")
  case let .presenceChanged(presence):
    print("Presence Received: \(presence)")
  case let .subscribeError(error):
    print("Subscription Error \(error)")
  default:
    break
  }
}

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

You can check the UUID of the publisher of a particular message by checking the message.publisher property in the subscription listener. You must also provide a default value for publisher, as the UUID parameter is optional.

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

SubscriptionEvent CaseEvent TypeStandalone ListenerEvent Description
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

This is an example using didReceiveBatchSubscription, to allow you to receive multiple events per event call

listener.didReceiveBatchSubscription = { events in
  for event in events {
    switch event {
    case .messageReceived(let message):
      print("The \(message.channel) channel received a message at \(message.published)")
      if let subscription = message.subscription {
        print("The channel-group or wildcard that matched this channel was \(subscription)")
      }
      print("The message is \(message.payload) and was sent by \(message.publisher ?? "")")
    case .signalReceived(let signal):
      print("The \(signal.channel) channel received a message at \(signal.published)")
      if let subscription = signal.subscription {
        print("The channel-group or wildcard that matched this channel was \(subscription)")
      }
      print("The signal is \(signal.payload) and was sent by \(signal.publisher ?? "")")
    case .connectionStatusChanged(let connectionChange):
      switch connectionChange {
      case .connecting:
        print("Status connecting...")
      case .connected:
        print("Status connected!")
      case .reconnecting:
        print("Status reconnecting...")
      case .disconnected:
        print("Status disconnected")
      case .disconnectedUnexpectedly:
        print("Status disconnected unexpectedly!")
      }
    case .subscriptionChanged(let subscribeChange):
      switch subscribeChange {
      case let .subscribed(channels, groups):
        print("\(channels) and \(groups) were added to subscription")
      case let .responseHeader(channels, groups, previous, next):
        print("\(channels) and \(groups) received a response at \(previous?.timetoken ?? 0)")
        print("\(next?.timetoken ?? 0) will be used as the new timetoken")
      case let .unsubscribed(channels, groups):
        print("\(channels) and \(groups) were removed from subscription")
      }
    case .presenceChanged(let presenceChange):
      print("The channel \(presenceChange.channel) has an updated occupancy of \(presenceChange.occupancy)")
      for action in presenceChange.actions {
        switch action {
        case let .join(uuids):
          print("The following list of occupants joined at \(presenceChange.timetoken): \(uuids)")
        case let .leave(uuids):
          print("The following list of occupants left at \(presenceChange.timetoken): \(uuids)")
        case let .timeout(uuids):
          print("The following list of occupants timed-out at \(presenceChange.timetoken): \(uuids)")
        case let .stateChange(uuid, state):
          print("\(uuid) changed their presence state to \(state) at \(presenceChange.timetoken)")
        }
      }
    case .uuidMetadataSet(let uuidMetadataChange):
      print("Changes were made to \(uuidMetadataChange.metadataId) at \(uuidMetadataChange.updated)")
      print("To apply the change, fetch a matching object and call `uuidMetadataChange.apply(to: otherUUIDMetadata)`")
    case .uuidMetadataRemoved(let metadataId):
      print("Metadata for the uuid \(metadataId) has been removed")
    case .channelMetadataSet(let channelMetadata):
      print("Changes were made to \(channelMetadata.metadataId) at \(channelMetadata.updated)")
      print("To apply the change, fetch a matching object and call `channelMetadata.apply(to: otherUUIDMetadata)`")
    case .channelMetadataRemoved(let metadataId):
      print("Metadata for the channel \(metadataId) has been removed")
    case .membershipMetadataSet(let membership):
      print("A membership was set between \(membership.uuidMetadataId) and \(membership.channelMetadataId)")
    case .membershipMetadataRemoved(let membership):
      print("A membership was removed between \(membership.uuidMetadataId) and \(membership.channelMetadataId)")
    case .messageActionAdded(let messageAction):
      print("The \(messageAction.channel) channel received a message at \(messageAction.messageTimetoken)")
      print("This action was created at \(messageAction.actionTimetoken)")
      print("This action has a type of \(messageAction.actionType) and has a value of \(messageAction.actionValue)")
    case .messageActionRemoved(let messageAction):
      print("The \(messageAction.channel) channel received a message at \(messageAction.messageTimetoken)")
      print("A message action with the timetoken of \(messageAction.actionTimetoken) has been removed")
    case .subscribeError(let error):
      print("The following error was generated during subscription \(error.localizedDescription)")
      print("If a `disconnectedUnexpectedly` also occurred then subscription has stopped, and needs to be restarted")
    }
  }
}

For didReceiveSubscription, simply rename the remove the for...in loop while keeping the event switch:

listener.didReceiveSubscription = { event in
  switch event {
  // Same content as the above example
  }
}