SwiftSwift Native Storage & Playback Tutorial 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.
Requires that the Storage and Playback add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
PubNub's Storage and Playback feature enables developers to store messages as they are published, and retrieve them at a later time. Before using this feature it must be enabled in the PubNub Admin Console.
Being able to pull an archive of messages from storage has many applications:
  • Populate chat, collaboration and machine configuration on app load.
  • Store message streams with real-time data management.
  • Retrieve historical data streams for reporting, auditing and compliance (HIPAA, SOX, Data Protection Directive, and more).
  • Replay live events with delivery of real-time data during rebroadcasting.
As needed, specific messages can be marked "do not archive" when published to prevent archiving on a per-message basis, and storage retention time can range from 1 day to forever.
These code samples build off code defined in the Pub & Sub tutorial, so before proceeding, be sure you have completed the Pub & Sub tutorial first.
To begin, lets populate a new channel with some test publishes that we'll pull from storage using the fetchMessageHistory() method.
 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.
listener.didReceiveStatus = { result in
  switch result {
  case .success(let connectionStatus):
    if connectionStatus.isActive {
      for index in 1...50 {
        let message = "message index: \(index)"
        pubnub.publish(
          channel: "channelSwift", 
          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)")
          }
        }
      }
    }
  }
  case .failure(let error):
    break
  }
}
In the above example, we subscribe to history_channel, and onConnect, we'll publish a barrage of test messages to it. You should see these messages as they are published on the console.
Now that we've populated storage, we can pull from storage using the fetchMessageHistory() method call:
pubnub.fetchMessageHistory(for: ["my_channel"]) { result in
  switch result {
  case let .success(response):
    print("Successful History Fetch Response: \(response)")
  case let .failure(error):
    print("Failed History Fetch Response: \(error.localizedDescription)")
  }
})
The response format is

[
	["message1", "message2", "message3",... ],
	"Start Time Token",
	"End Time Token"
]
By default, fetchMessageHistory() returns the last 100 messages, first-in-first-out (FIFO). Although we specified 100 for the max, that is the default, and if we hadn't specified a max, we would have still received 100. Try this example again, but specify 5 for max to see what is returned.
The timetoken response value is a string, representing 17-digit precision unix time (UTC). To convert PubNub's timetoken to Unix timestamp (seconds), divide the timetoken number by 10,000,000 (10^7).
Given this example, you will get the last two messages published to the channel:
pubnub.fetchMessageHistory(
  for: ["channelSwift"],
  max: 2
) { result in
  switch result {
  case let .success(response):
    print("Successful History Fetch Response: \(response)")
  case let .failure(error):
    print("Failed History Fetch Response: \(error.localizedDescription)")
  }
}
[[498,499],14272454823679518,14272454845442942]
To page for the next 2, use the set the start attribute to start timetoken value, and request again with all other settings the same:
[[496,497],14272454791882580,14272454823679518]
pubnub.fetchMessageHistory(
  for: ["channelSwift", "otherChannel", "myChannel"],
  max: 25
) { result in
  switch result {
  case let .success(response):
    print("Successful History Fetch Response: \(response)")
  case let .failure(error):
    print("Failed History Fetch Response: \(error.localizedDescription)")
  }
}
To pull from a slice of time, just include both start and end attributes:
pubnub.fetchMessageHistory(
  for: ["channelSwift"],
  start: "13406310091110311"
  end: "13406746780720711"
) { result in
  switch result {
  case let .success(response):
    print("Successful History Fetch Response: \(response)")
  case let .failure(error):
    print("Failed History Fetch Response: \(error.localizedDescription)")
  }
}