Message Persistence API for Swift Native SDK
Message Persistence gives you real-time access to the history of messages published to PubNub. Each message is timestamped to the nearest 10 nanoseconds and stored across multiple availability zones in several geographic locations. You can encrypt stored messages with AES-256 so they are not readable on PubNub’s network. For details, see Message Persistence.
You control how long messages are stored through your account’s retention policy. Options include: 1 day, 7 days, 30 days, 3 months, 6 months, 1 year, or Unlimited.
You can retrieve the following:
- Messages
- Message reactions
- Files (using the File Sharing API)
Fetch history
Requires Message Persistence
This method requires that Message Persistence is enabled for your key in the Admin Portal.
Fetch historical messages from one or more channels. Use includeMessageActions to include message actions.
It's possible to control how messages are returned and in what order.
- If you specify only
start, you receive messages older than that timetoken.startis the newer boundary of the query (exclusive). - If you specify only
end, you receive messages newer than or equal to that timetoken.endis the older boundary of the query (inclusive). - If you specify both
startandend,startmust be a higher timetoken thanend. Results contain messages between those timetokens, excluding the message atstartand including the message atend.
How to use the start and end parameters
PubNub retrieves messages by searching backward through time (newest to oldest). Because of this, the parameter names are the reverse of their intuitive meaning:
startis the newer boundary (higher timetoken value) - search begins here, exclusiveendis the older boundary (lower timetoken value) - search stops here, inclusive
When you provide both parameters, start must be a higher timetoken than end.
Results are always returned in oldest-first order.
This function returns up to 100 messages on a single channel, or 25 per channel on up to 500 channels. To page, iteratively update the start timetoken.
Method(s)
Use the following method(s) in the Swift SDK:
1func fetchMessageHistory(
2 for channels: [String],
3 includeActions actions: Bool = false,
4 includeMeta: Bool = false,
5 includeUUID: Bool = true,
6 includeMessageType: Bool = true,
7 includeCustomMessageType: Bool = false,
8 page: PubNubBoundedPage? = PubNubBoundedPageBase(),
9 custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
10 completion: ((Result<(messagesByChannel: [String: [PubNubMessage]], next: PubNubBoundedPage?), Error>) -> Void)?
11)
forrequired#- The list of channels to fetch history messages from. Maximum of 500 channels are allowed.
includeActions#- If
trueany Message Actions will be included in the response. When set totruethe method is limited to retrieving history from a single channel. includeMeta#- If
truethe meta properties of messages will be included in the response. includeUUID#- If
truethe user ID of the sender will be included in the response. includeMessageType#- Indicates whether to retrieve messages with PubNub message type.
For more information, refer to Retrieving Messages. includeCustomMessageType#- Indicates whether to retrieve messages with the custom message type.
For more information, refer to Retrieving Messages. page#- The paging object used for pagination. It allows you to specify a range of messages to retrieve based on specific time bounds. Set
limitto control the number of results per page. Maximum value is 100 for a single channel, 25 for multiple channels, and 25 whenincludeActionsistrue. custom#- An object that allows for per-request customization of PubNub configuration or network session. For more information, refer to the Request Configuration section.
completion#- The async
Resultof the method call.
Truncated response
If truncated, a next property is returned with additional parameters. Make iterative calls adjusting parameters.
Completion handler result
Success
A dictionary of channels mapped to their message lists, and the next page cursor when available.
1public protocol PubNubMessage {
2
3 /// The message sent on the channel
4 var payload: JSONCodable { get set }
5
6 /// Message reactions associated with this message
7 var actions: [PubNubMessageAction] { get set }
8
9 /// Message sender identifier
10 var publisher: String? { get set }
11
12 /// The channel for which the message belongs
13 var channel: String { get }
14
15 /// The channel group or wildcard subscription match (if exists)
show all 41 lines1public protocol PubNubBoundedPage {
2
3 /// The start value for the next set of remote data
4 var start: Timetoken? { get }
5
6 /// The bounded end value that will be eventually fetched to
7 var end: Timetoken? { get }
8
9 /// The previous limiting value (if any)
10 var limit: Int? { get }
11}
Failure
An error describing the failure.
Sample code
Retrieve the last message on a channel:
1import PubNubSDK
2
3// Initializes a PubNub object with the configuration
4let pubnub = PubNub(
5 configuration: PubNubConfiguration(
6 publishKey: "demo",
7 subscribeKey: "demo",
8 userId: "myUniqueUserId"
9 )
10)
11
12// Retrieve messages from a channel
13pubnub.fetchMessageHistory(for: ["my_channel"]) { result in
14 switch result {
15 case let .success(response):
show all 28 linesOther examples
Retrieve messages newer or equal than a given timetoken
1// Retrieve messages that are newer or equal to a specific timetoken
2pubnub.fetchMessageHistory(
3 for: ["my_channel"],
4 page: PubNubBoundedPageBase(end: 13406746780720711)
5) { result in
6 switch result {
7 case let .success(response):
8 if let myChannelMessages = response.messagesByChannel["my_channel"] {
9 // Iterating over each message in the channel and printing its payload
10 myChannelMessages.forEach { historicalMessage in
11 print("Message payload: \(historicalMessage.payload)")
12 }
13 }
14 if let nextPage = response.next {
15 print("The next page used for pagination: \(nextPage)")
show all 20 linesRetrieve messages older than a specific timetoken
1// Retrieve messages older than a specific timetoken (exclusive).
2// Exclusive means that the message associated with the `13406746780720711` timetoken will be excluded from the result.
3pubnub.fetchMessageHistory(
4 for: ["my_channel"],
5 page: PubNubBoundedPageBase(start: 13406746780720711)
6) { result in
7 switch result {
8 case let .success(response):
9 if let myChannelMessages = response.messagesByChannel["my_channel"] {
10 // Iterating over each message in the channel and printing its payload
11 myChannelMessages.forEach { historicalMessage in
12 print("Message payload: \(historicalMessage.payload)")
13 }
14 }
15 if let nextPage = response.next {
show all 21 linesRetrieve the last 10 messages on channelSwift, otherChannel, and myChannel
1// Retrieve messages from multiple channels with a limit on the number of messages returned
2pubnub.fetchMessageHistory(
3 for: ["channelSwift", "otherChannel", "myChannel"],
4 page: PubNubBoundedPageBase(limit: 10)
5) { result in
6 switch result {
7 case let .success(response):
8 response.messagesByChannel.forEach { channel, messages in
9 print("Channel `\(channel)` has the following messages: \(messages)")
10 }
11 if let nextPage = response.next {
12 print("The next page used for pagination: \(nextPage)")
13 }
14 case let .failure(error):
15 print("Failed History Fetch Response: \(error.localizedDescription)")
show all 17 linesRetrieve messages and their metadata
1// Retrieve messages from a channel with metadata
2pubnub.fetchMessageHistory(
3 for: ["my_channel"],
4 includeMeta: true
5) { result in
6 switch result {
7 case let .success(response):
8 if let myChannelMessages = response.messagesByChannel["my_channel"] {
9 // Iterating over each message in the channel to print its payload and metadata
10 myChannelMessages.forEach { message in
11 print("Message sent at \(message.published):")
12 print("Payload: \(message.payload)")
13 print("Metadata: \(String(describing: message.metadata))")
14 }
15 }
show all 22 linesRetrieve messages and their message action data
1// Retrieve messages from a channel with actions
2pubnub.fetchMessageHistory(
3 for: ["my_channel"],
4 includeActions: true
5) { result in
6 switch result {
7 case let .success(response):
8 if let myChannelMessages = response.messagesByChannel["my_channel"] {
9 myChannelMessages.forEach { message in
10 print("Message sent at \(message.published):")
11 print("Actions: \(message.actions)")
12 }
13 }
14 if let nextPage = response.next {
15 print("The next page used for pagination: \(nextPage)")
show all 20 linesDelete messages from history
Requires Message Persistence
This method requires that Message Persistence is enabled for your key in the Admin Portal.
Removes the messages from the history of a specific channel.
Required setting
Enable Delete-From-History in key settings and initialize with a secret key.
How to use the start and end parameters
PubNub retrieves messages by searching backward through time (newest to oldest). Because of this, the parameter names are the reverse of their intuitive meaning:
startis the newer boundary (higher timetoken value) - search begins here, exclusiveendis the older boundary (lower timetoken value) - search stops here, inclusive
When you provide both parameters, start must be a higher timetoken than end.
Results are always returned in oldest-first order.
Method(s)
To Delete Messages from History you can use the following method(s) in the Swift SDK.
1func deleteMessageHistory(
2 from channel: String,
3 start: Timetoken? = nil,
4 end: Timetoken? = nil,
5 custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
6 completion: ((Result<Void, Error>) -> Void)?
7)
fromrequired#- The channel to delete the messages from.
start#- Newer boundary of the query (exclusive). Must be a higher timetoken value than
endwhen both are provided. end#- Older boundary of the query (inclusive). Must be a lower timetoken value than
startwhen both are provided. custom#- An object that allows for per-request customization of PubNub configuration or network session. For more information, refer to the Request Configuration section.
completion#- The async
Resultof the method call
Completion handler result
Success
A Void indicating a success.
Failure
An Error describing the failure.
Sample code
1// Delete all messages from a channel
2pubnub.deleteMessageHistory(
3 from: "my_channel"
4) { result in
5 switch result {
6 case .success:
7 print("The message deletion was successful")
8 case let .failure(error):
9 print("Failed Message Deletion Response: \(error.localizedDescription)")
10 }
11}
Other examples
Delete specific message from history
1// Delete a specific message from a channel
2pubnub.deleteMessageHistory(
3 from: "my_channel",
4 start: 15526611838554309,
5 end: 15526611838554310
6) { result in
7 switch result {
8 case .success:
9 print("The message deletion was successful")
10 case let .failure(error):
11 print("Failed Message Deletion Response: \(error.localizedDescription)")
12 }
13}
Message counts
Requires Message Persistence
This method requires that Message Persistence is enabled for your key in the Admin Portal.
Return the number of messages published since the given time; the count is messages with timetoken ≥ the provided value.
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:
1func messageCounts(
2 channels: [String: Timetoken],
3 custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
4 completion: ((Result<[String: Int], Error>) -> Void)?
5)
channelsrequired#- The map of channels and the
timetokento get the message count for. custom#- An object that allows for per-request customization of PubNub configuration or network session. For more information, refer to the Request Configuration section.
completion#- The async
Resultof the method call.
1func messageCounts(
2 channels: [String],
3 timetoken: Timetoken = 1,
4 custom requestConfig: PubNub.RequestConfiguration = PubNub.RequestConfiguration(),
5 completion: ((Result<[String: Int], Error>) -> Void)?
6)
channelsrequired#- The list of channels to get message counts for.
timetoken#- The
timetokenfor all channels in the list to get message counts for. custom#- An object that allows for per-request customization of PubNub configuration or network session. For more information, refer to the Request Configuration section.
completion#- The async
Resultof the method call.
Completion handler result
Success
A Dictionary of channels mapped to their respective message count.
Failure
An Error describing the failure.
Sample code
1// Retrieve the message count for a channel
2pubnub.messageCounts(channels: ["my_channel"]) { result in
3 switch result {
4 case let .success(messageCountByChannel):
5 if let myChannelCount = messageCountByChannel["my_channel"] {
6 print("The current message count for `my_channel` is \(myChannelCount)")
7 }
8 case let .failure(error):
9 print("Failed Message Count Response: \(error.localizedDescription)")
10 }
11}
Other examples
Retrieve message counts for multiple channels with the same timetoken 15526611838554310
1// Retrieve the message count for multiple channels
2pubnub.messageCounts(
3 channels: ["my_channel", "other_channel", "their_channel"],
4 timetoken: 15526611838554310
5) { result in
6 switch result {
7 case let .success(messageCountByChannel):
8 messageCountByChannel.forEach { channel, messageCount in
9 print("The current message count for `\(channel)` is \(messageCount)")
10 }
11 case let .failure(error):
12 print("Failed Message Count Response: \(error.localizedDescription)")
13 }
14}
Retrieve message counts for multiple channels with different timetokens
1// Retrieve the message count for multiple channels with different timetokens
2pubnub.messageCounts(
3 channels: [
4 "my_channel": 15526611838554309,
5 "other_channel": 15526611838554310,
6 "their_channel": 1
7 ]
8) { result in
9 switch result {
10 case let .success(messageCountByChannel):
11 messageCountByChannel.forEach { channel, messageCount in
12 print("The current message count for `\(channel)` is \(messageCount)")
13 }
14 case let .failure(error):
15 print("Failed Message Count Response: \(error.localizedDescription)")
show all 17 lines