Jhn Jhn - 2 years ago 1286
Swift Question

Swift iOS: Firebase Paging

I have this Firebase data:

Firebase Data

I want to query the

data through pagination. Currently my code is converting this JS code to Swift code

let postsRef = self.rootDatabaseReference.child("development/posts")
postsRef.queryOrderedByChild("createdAt").queryStartingAtValue((page - 1) * count).queryLimitedToFirst(UInt(count)).observeSingleEventOfType(.Value, withBlock: { snapshot in


When accessing, this data
page: 1, count: 1
. I can get the data for "posts.a" but when I try to access
page: 2, count: 1
the returns is still "posts.a"

What am I missing here?

Answer Source

Assuming that you are or will be using childByAutoId() when pushing data to Firebase, you can use queryOrderedByKey() to order your data chronologically. Doc here.

The unique key is based on a timestamp, so list items will automatically be ordered chronologically.

To start on a specific key, you will have to append your query with queryStartingAtValue(_:).

Sample usage:

var count = numberOfItemsPerPage

var query ref.queryOrderedByKey()

if startKey != nil {
  query = query.queryStartingAtValue(startKey)
  count += 1

query.queryLimitedToFirst(UInt(count)).observeSingleEventOfType(.Value, withBlock: { snapshot in
  guard var children = snapshot.children.allObjects as? [FIRDataSnapshot] else {
    // Handle error

  if startKey != nil && !children.isEmpty {

  // Do something with children
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download