SwiftSwift Native Storage & Playback 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 PubNub Storage and Playback Service provides realtime access to history for all messages published to PubNub. Each published message is timestamped to the nearest 10 nanoseconds, and is stored across multiple availability zones in several geographical data center locations. Stored messages can be encrypted with AES-256 message encryption, ensuring that they are not readable while stored on PubNub's network.

Messages can be stored for a configurable duration or forever, as controlled by the retention policy that is configured on your account. The following options are available: 1 day, 7 days, 1 month, and Forever.


Requires Storage & Playback add-on XRequires that the Storage & Playback 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.

This function fetches historical messages from multiple channels. The includeMessageActions or includeActions flag also allows you to fetch message actions along with the messages.

It's possible to control how messages are returned and in what order. For example, you can:

  • Search for messages starting on the newest end of the timeline.
  • Search for messages from the oldest end of the timeline.
  • Page through results by providing a start OR end time token.
  • Retrieve a slice of the time line by providing both a start AND end time token.
  • Retrieve a specific (maximum) number of messages using the PubNubBoundedPage(limit) parameter.

Batch history returns up to 100 messages on a single channel, or 25 per channel on a maximum of 500 channels. Use the start and end timestamps to page through the next batch of messages.

Start and End parameter usage clarity

If you specify only the start parameter (without end), you will receive messages that are older than the start timetoken.

If you specify only the end parameter (without start), you will receive messages from that end timetoken and newer.

Specify values for both start and end parameters to retrieve messages between those timetokens (inclusive of the end value).

Keep in mind that you will still receive a maximum of 100 messages (or 25, for multiple channels) even if there are more messages that meet the timetoken values. Iterative calls to history adjusting the start timetoken are necessary to page through the full set of results if more messages meet the timetoken values.

To run Fetch History, you can use the following method(s) in the Swift SDK:
  1. ParameterTypeRequiredDefaultsDescription
    for[String]YesThe list of channels to fetch history messages from.
    includeActionsBoolOptionalfalseIf true any Message Actions will be included in the response. When set to true the method is limited to retrieving history from a single channel.
    includeMetaBoolOptionalfalseIf true the meta properties of messages will be included in the response
    pagePubNubBoundedPage?OptionalPubNubBoundedPageBase()The paging object used for pagination. Set limit to control the number of results per page. Maximum value is 100 for a single channel, 25 for multiple channels, and 25 when includeActions is true.
    customRequestConfigurationOptionalRequestConfiguration()An object that allows for per-request customization of PubNub Configuration or Network Session
    completion((Result<(messagesByChannel: [String: [PubNubMessage]], next: PubNubBoundedPage?), Error>) -> Void)?OptionalnilThe async Result of the method call

    Completion Handler Result

    • Success: A Tuple of a Dictionary of channels mapped to an Array their respective PubNubMessages, and the next request PubNubBoundedPage (if one exists).

      public protocol PubNubMessage {
        /// The message sent on the channel
        var payload: JSONCodable { get set }
      
        /// Message actions associated with this message
        var actions: [PubNubMessageAction] { get set }
      
        /// The channel for which the message belongs
        var channel: String { get }
      
        /// Timetoken for the message
        var published: Timetoken { get set }
      
        /// Meta information for the message
        var metadata: JSONCodable? { get set }
      }
      public protocol PubNubBoundedPage {
        /// The start value for the next set of remote data
        var start: Timetoken? { get }
      
        /// The bounded end value that will be eventually fetched to
        var end: Timetoken? { get }
      
        /// The previous limiting value (if any)
        var limit: Int? { get }
      }
    • Failure: An Error describing the failure.
Retrieve the last message on a channel:
pubnub.fetchMessageHistory(for: ["my_channel"]) { result in
  switch result {
  case let .success(response):
    if let myChannelMessages = response.messagesByChannel["my_channel"] {
      print("The list of messages returned for `my_channel`: \(myChannelMessages)")
    }
    if let nextPage = response.next {
      print("The next page used for pagination: \(nextPage)")
    }
  case let .failure(error):
    print("Failed History Fetch Response: \(error.localizedDescription)")
  }
})
  1. pubnub.fetchMessageHistory(
      for: ["my_channel"],
      page: PubNubBoundedPageBase(end: 13406746780720711)
    ) { result in
      switch result {
      case let .success(response):
        if let myChannelMessages = response.messagesByChannel["my_channel"] {
          print("The list of messages returned for `my_channel`: \(myChannelMessages)")
        }
        if let nextPage = response.next {
          print("The next page used for pagination: \(nextPage)")
        }
      case let .failure(error):
        print("Failed History Fetch Response: \(error.localizedDescription)")
      }
    }
  2. pubnub.fetchMessageHistory(
      for: ["my_channel"],
      page: PubNubBoundedPageBase(start: 13406746780720711)
    ) { result in
      switch result {
      case let .success(response):
        if let myChannelMessages = response.messagesByChannel["my_channel"] {
          print("The list of messages returned for `my_channel`: \(myChannelMessages)")
        }
        if let nextPage = response.next {
          print("The next page used for pagination: \(nextPage)")
        }
      case let .failure(error):
        print("Failed History Fetch Response: \(error.localizedDescription)")
      }
    }
  3. pubnub.fetchMessageHistory(
      for: ["channelSwift", "otherChannel", "myChannel"],
      page: PubNubBoundedPageBase(limit: 10)
    ) { result in
      switch result {
      case let .success(response):
        response.messagesByChannel.forEach { (channel, messages) in
          print("Channel `\(channel)` has the following messages: \(messages)")
        }
        if let nextPage = response.next {
          print("The next page used for pagination: \(nextPage)")
        }
      case let .failure(error):
        print("Failed History Fetch Response: \(error.localizedDescription)")
      }
    }
  4. pubnub.fetchMessageHistory(
      for: ["my_channel"],
      includeMeta: true
    ) { result in
      switch result {
      case let .success(response):
        if let myChannelMessages = response.messagesByChannel["my_channel"] {
          print("The list of messages returned for `my_channel`: \(myChannelMessages)")
          myChannelMessages.forEach { message in
            print("The message sent at \(message.published) has the following metadata \(message.metadata)")
          }
        }
        if let nextPage = response.next {
          print("The next page used for pagination: \(nextPage)")
        }
      case let .failure(error):
        print("Failed History Fetch Response: \(error.localizedDescription)")
      }
    }
  5. pubnub.fetchMessageHistory(
      for: ["my_channel"],
      includeActions: true
    ) { result in
      switch result {
      case let .success(response):
          if let myChannelMessages = response.messagesByChannel["my_channel"] {
            print("The list of messages returned for `my_channel`: \(myChannelMessages)")
            myChannelMessages.forEach { message in
              print("The message sent at \(message.published) has the following actions \(message.actions)")
            }
          }
          if let nextPage = response.next {
            print("The next page used for pagination: \(nextPage)")
          }
      case let .failure(error):
        print("Failed History Fetch Response: \(error.localizedDescription)")
      }
    }

Requires Storage & Playback add-on XRequires that the Storage & Playback 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.
Removes the messages from the history of a specific channel.
 
There is a setting to accept delete from history requests for a key, which you must enable by checking the Enable Delete-From-History checkbox in the key settings for your key in the Admin Portal.

Requires Initialization with secret key.

To Delete Messages from History you can use the following method(s) in the Swift SDK.
  1. ParameterTypeRequiredDefaultsDescription
    fromStringYesThe channel to delete the messages from.
    startTimetoken?OptionalnilTime token delimiting the start of time slice (inclusive) to delete messages from.
    endTimetoken?OptionalnilTime token delimiting the end of time slice (exclusive) to delete messages from.
    customRequestConfigurationOptionalRequestConfiguration()An object that allows for per-request customization of PubNub Configuration or Network Session
    completion((Result<Void, Error>) -> Void)?OptionalnilThe async Result of the method call

    Completion Handler Result

    • Success: A Void indicating a success.
    • Failure: An Error describing the failure.
pubnub.deleteMessageHistory(
  from: "my_channel"
) { result in
  switch result {
  case let .success:
    print("The message deletion was successful")
  case let .failure(error):
    print("Failed Message Deletion Response: \(error.localizedDescription)")
  }
}
  1. pubnub.deleteMessageHistory(
      from: "my_channel",
      start: 15526611838554310,
      end: 15526611838554309
    ) { result in
      switch result {
      case let .success:
        print("The message deletion was successful")
      case let .failure(error):
        print("Failed Message Deletion Response: \(error.localizedDescription)")
      }
    }

Requires Storage & Playback add-on XRequires that the Storage & Playback 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.
Returns the number of messages published on one or more channels since a given time. The count returned is the number of messages in history with a timetoken value greater than the passed value in the timetokenparameter.
 For keys with unlimited message retention enabled, this method considers only messages published in the last 7 days.
You can use the following method(s) in the Swift SDK:
  1. ParameterTypeRequiredDefaultsDescription
    channels[String: Timetoken]YesThe map of channels and the Timetoken to get the message count for
    customRequestConfigurationOptionalRequestConfiguration()An object that allows for per-request customization of PubNub Configuration or Network Session
    completion((Result<[String: Int], Error>) -> Void)?OptionalnilThe async Result of the method call
  2. ParameterTypeRequiredDefaultsDescription
    channels[String]YesThe list of channels to get message counts for.
    timetokenTimetokenOptional1The timetoken for all channels in the list to get message counts for.
    customRequestConfigurationOptionalRequestConfiguration()An object that allows for per-request customization of PubNub Configuration or Network Session
    completion((Result<[String: Int], Error>) -> Void)?OptionalnilThe async Result of the method call

    Completion Handler Result

    • Success: A Dictionary of channels mapped to their respective message count.
    • Failure: An Error describing the failure.
pubnub.messageCounts(channels: ["my_channel"]) { result in
  switch result {
  case let .success(messageCountByChannel):
    if let myChannelCount = messageCountByChannel["my_channel"] {
      print("The current message count for `my_channel` is \(myChannelCount)")
    }
  case let .failure(error):
    print("Failed Message Count Response: \(error.localizedDescription)")
  }
}
  1. pubnub.messageCounts(
      channels: ["my_channel", "other_channel", "their_channel"],
      timetoken: 15526611838554310
    ) { result in
      switch result {
      case let .success(messageCountByChannel):
        messageCountByChannel.forEach { (channel, messageCount) in
          print("The current message count for `\(channel)` is \(messageCount)")
        }
      case let .failure(error):
        print("Failed Message Count Response: \(error.localizedDescription)")
      }
    }
  2. pubnub.messageCounts(
      channels: [
        "my_channel": 15526611838554310,
        "other_channel": 15526611838554309,
        "their_channel": 1
      ]
    ) { result in
      switch result {
      case let .success(messageCountByChannel):
        messageCountByChannel.forEach { (channel, messageCount) in
          print("The current message count for `\(channel)` is \(messageCount)")
        }
      case let .failure(error):
        print("Failed Message Count Response: \(error.localizedDescription)")
      }
    }