Message Persistence API for PubNub Swift Native SDK
Message Persistence provides real-time access to the history of 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 locations. Stored messages can be encrypted with AES-256 message encryption, ensuring that they are not readable while stored on PubNub's network. For more information, refer to Message Persistence.
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, 30 days, 3 months, 6 months, 1 year, or Unlimited.
You can retrieve the following:
- Messages
- Message reactions
- File Sharing (using File Sharing API)
Fetch History
Requires Message Persistence
This method requires that Message Persistence is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
This function fetches historical messages from one or multiple channels. The includeMessageActions
flag also allows you to fetch message reactions along with the messages.
It's possible to control how messages are returned and in what order.
- if you specify only the
start
parameter (withoutend
), you will receive messages that are older than thestart
timetoken - if you specify only the
end
parameter (withoutstart
), you will receive messages from thatend
timetoken and newer - if you specify values for both
start
andend
parameters, you will retrieve messages between those timetokens (inclusive of theend
value)
You will receive a maximum of 100 messages for a single channel or 25 messages for multiple channels (up to 500). If more messages meet the timetoken criteria, make iterative calls while adjusting the start
timetoken to fetch the entire list of messages from Message Persistence.
Method(s)
To run Fetch History
, you can use the following method(s) in the Swift SDK:
fetchMessageHistory(
for channels: [String],
includeActions actions: Bool = false,
includeMeta: Bool = false,
includeUUID: Bool = true,
includeMessageType: Bool = true,
includeCustomMessageType: Bool = false,
page: PubNubBoundedPage? = PubNubBoundedPageBase(),
custom requestConfig: RequestConfiguration = RequestConfiguration(),
completion: ((Result<(messagesByChannel: [String: [PubNubMessage]], next: PubNubBoundedPage?), Error>) -> Void)?
)
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
for | [String] | Yes | The list of channels to fetch history messages from. Maximum of 500 channels are allowed. | |
includeActions | Bool | Optional | false | If true any Message Reactions will be included in the response. When set to true the method is limited to retrieving history from a single channel. |
includeMeta | Bool | Optional | false | If true the meta properties of messages will be included in the response. |
includeUUID | Bool | Optional | true | If true the user ID of the sender will be included in the response. |
includeMessageType | Bool | Optional | true | Indicates whether to retrieve messages with PubNub message type. For more information, refer to Retrieving Messages. |
includeCustomMessageType | Bool | Optional | false | Indicates whether to retrieve messages with the custom message type. For more information, refer to Retrieving Messages. |
page | PubNubBoundedPage? | Optional | PubNubBoundedPageBase() | The paging object used for pagination. It allows you to specify a range of messages to retrieve based on specific time bounds. 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 . |
custom | RequestConfiguration | Optional | RequestConfiguration() | An object that allows for per-request customization of PubNub Configuration or Network Session |
completion | ((Result<(messagesByChannel: [String: [PubNubMessage]], next: PubNubBoundedPage?), Error>) -> Void)? | Optional | nil | The async Result of the method call |
Truncated response
If you fetch messages with messages actions, the number of messages in the response may be truncated when internal limits are hit. If the response is truncated, a more
property will be returned with additional parameters. Send iterative calls to history adjusting the parameters to fetch more messages.
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 }
/// The type of message that was received
var messageType: PubNubMessageType { get set }
/// A user-provided custom message type
var customMessageType: String? { get set }
/// Message reactions associated with this message
var actions: [PubNubMessageAction] { get set }
/// The channel for which the message belongs
var channel: String { get }
show all 22 linespublic 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.
Basic Usage
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)")
}
})
Other Examples
Retrieve messages newer than a given timetoken
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)")
}
show all 16 linesRetrieve messages starting from a specific timetoken
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)")
}
show all 16 linesRetrieve the last 10 messages on channelSwift, otherChannel, and myChannel
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)")
}
show all 16 linesRetrieve messages and their metadata
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)")
}
show all 19 linesRetrieve messages and their Message Reaction data
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)")
}
show all 19 linesDelete Messages from History
Requires Message Persistence
This method requires that Message Persistence is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.
Removes the messages from the history of a specific channel.
Required setting
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.
Method(s)
To Delete Messages from History
you can use the following method(s) in the Swift SDK.
deleteMessageHistory(
from channel: String,
start: Timetoken? = nil,
end: Timetoken? = nil,
custom requestConfig: RequestConfiguration = RequestConfiguration(),
completion: ((Result<Void, Error>) -> Void)?
)
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
from | String | Yes | The channel to delete the messages from. | |
start | Timetoken? | Optional | nil | Timetoken delimiting the start of time slice (inclusive) to delete messages from. |
end | Timetoken? | Optional | nil | Timetoken delimiting the end of time slice (exclusive) to delete messages from. |
custom | RequestConfiguration | Optional | RequestConfiguration() | An object that allows for per-request customization of PubNub Configuration or Network Session |
completion | ((Result<Void, Error>) -> Void)? | Optional | nil | The async Result of the method call |
Completion Handler Result
Success
A Void
indicating a success.
Failure
An Error
describing the failure.
Basic Usage
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)")
}
}
Other Examples
Delete specific message from history
pubnub.deleteMessageHistory(
from: "my_channel",
start: 15526611838554309,
end: 15526611838554310
) { result in
switch result {
case let .success:
print("The message deletion was successful")
case let .failure(error):
print("Failed Message Deletion Response: \(error.localizedDescription)")
}
}
Message Counts
Requires Message Persistence
This method requires that Message Persistence is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your 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 or equal to
than the passed value in the timetoken
parameter.
Unlimited message retention
For keys with unlimited message retention enabled, this method considers only messages published in the last 30 days.
Method(s)
You can use the following method(s) in the Swift SDK:
messageCounts(
channels: [String: Timetoken],
custom requestConfig: RequestConfiguration = RequestConfiguration(),
completion: ((Result<[String: Int], Error>) -> Void)?
)
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
channels | [String: Timetoken] | Yes | The map of channels and the Timetoken to get the message count for | |
custom | RequestConfiguration | Optional | RequestConfiguration() | An object that allows for per-request customization of PubNub Configuration or Network Session |
completion | ((Result<[String: Int], Error>) -> Void)? | Optional | nil | The async Result of the method call |
messageCounts(
channels: [String],
timetoken: Timetoken = 1,
custom requestConfig: RequestConfiguration = RequestConfiguration(),
completion: ((Result<[String: Int], Error>) -> Void)?
)
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
channels | [String] | Yes | The list of channels to get message counts for. | |
timetoken | Timetoken | Optional | 1 | The timetoken for all channels in the list to get message counts for. |
custom | RequestConfiguration | Optional | RequestConfiguration() | An object that allows for per-request customization of PubNub Configuration or Network Session |
completion | ((Result<[String: Int], Error>) -> Void)? | Optional | nil | The 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.
Basic Usage
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)")
}
}
Other Examples
Retrieve message counts for multiple channels with the same timetoken 15526611838554310
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)")
}
}
Retrieve message counts for multiple channels with different timetokens
pubnub.messageCounts(
channels: [
"my_channel": 15526611838554309,
"other_channel": 15526611838554310,
"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)")
}
show all 16 lines