On this page

Message history

PubNub APIs let you effectively fetch historical messages from direct, group, or public conversations.

While App Context API lets you manage metadata and relationships between users and channels, enabling efficient tracking of which channels are associated with a given user, Message Persistence API lets you retrieve messages from those channels. Together, these APIs enable you to gather all conversations involving a user and easily fetch specific message histories for any interactions between users.

Use getHistory() to fetch past messages from a channel.

API limitation

Results cannot be filtered by message type. All messages within the specified timeframe are returned.

Method signature

This method takes the following parameters:

1channel.getHistory(
2 startTimetoken: Timetoken? = nil,
3 endTimetoken: Timetoken? = nil,
4 count: Int = 25
5 ) async throws -> (messages: [MessageImpl], isMore: Bool)

Input

How to use the startTimetoken and endTimetoken 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:

  • startTimetoken is the newer boundary (higher timetoken value) - search begins here, exclusive
  • endTimetoken is the older boundary (lower timetoken value) - search stops here, inclusive

When you provide both parameters, startTimetoken must be a higher timetoken than endTimetoken.

9:00 AM10:00 AM11:00 AM11:59 AM

Results are always returned in oldest-first order.

* required
ParameterDescription
startTimetoken
Type: Timetoken
Default:
n/a
Timetoken delimiting the start of a time slice (exclusive) to pull messages from. For details, refer to the Fetch History section.
endTimetoken
Type: Timetoken
Default:
n/a
Timetoken delimiting the end of a time slice (inclusive) to pull messages from. For details, refer to the Fetch History section.
count
Type: Int
Default:
25
Number of historical messages to return for the channel in a single call. Since each call returns all attached message reactions by default, the maximum number of returned messages is 25. For more details, refer to the description of the includeMessageActions parameter in the Swift SDK docs.

Output

ParameterDescription
(messages: [MessageImpl], isMore: Bool)
A tuple containing a list of MessageImpl objects and a boolean flag indicating if there are more messages available.

By default, each call returns all message reactions and metadata attached to the retrieved messages.

Sample code

Sample code

The code samples in Swift Chat SDK focus on asynchronous code execution.

You can also write synchronous code as the parameters are shared between the async and sync methods but we don't provide usage examples of such.

From the support channel, fetch 10 historical messages older than the timetoken 15343325214676133.

1