I am implementing pagination in my iOS Swift app with Firebase Firestore, and I am having points with backwards navigation. When clicking the “earlier web page” button, it reveals newer objects as a substitute of older ones.
This is my present implementation:
func loadNextPage() {
guard let lastDocument = lastDocument else { return }
isLoading = true
currentPage += 1
var question = db.assortment("objects")
.order(by: "timestamp", descending: true)
.begin(afterDocument: lastDocument)
.restrict(to: itemsPerPage)
// Apply filters...
question.getDocuments { [weak self] snapshot, error in
// Deal with outcomes...
self.objects = snapshot.paperwork.compactMap { self.documentToItem($0) }
self.lastDocument = snapshot.paperwork.final
}
}
func loadPreviousPage() {
guard !isLoading else { return }
isLoading = true
currentPage -= 1
var question = db.assortment("objects")
.order(by: "timestamp", descending: true)
if let firstItem = objects.first {
question = question.whereField("timestamp", isGreaterThan: firstItem.timestamp)
.restrict(to: itemsPerPage)
}
// Apply filters...
question.getDocuments { [weak self] snapshot, error in
// Deal with outcomes...
self.objects = snapshot.paperwork.compactMap { self.documentToItem($0) }
self.lastDocument = snapshot.paperwork.final
}
}
What I’ve tried thus far:
-
Utilizing begin(after:) with the primary merchandise’s timestamp:
swiftquestion = question.begin(after: [firstItem.timestamp])
-
Utilizing finish(earlier than:) with the primary merchandise’s timestamp:
question = question.finish(earlier than: [firstItem.timestamp])
-
Altering the order path for earlier web page:
question = db.assortment("objects") .order(by: "timestamp", descending: false)
-
Utilizing whereField with totally different comparisons:
swiftquestion = question.whereField("timestamp", isLessThan: firstItem.timestamp)
The pagination works completely when going ahead, however when attempting to go backwards:
- Typically it reveals the identical objects as the subsequent web page
- Typically it jumps to the primary web page
- Typically it reveals newer objects as a substitute of older ones
My knowledge construction in Firestore:
Assortment with paperwork
Every doc has a timestamp area (server timestamp)
Utilizing descending order by timestamp
Limiting to N objects per web page
How can I implement correct backwards pagination that reveals the earlier N objects chronologically?