Swift iOS: Firebase Paging

后端 未结 2 1616
灰色年华
灰色年华 2020-12-14 04:41

I have this Firebase data:

I want to query the posts data through pagination. Currently my code is converting this JS code to Swift code



        
2条回答
  •  佛祖请我去吃肉
    2020-12-14 05:16

    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
        return
      }
    
      if startKey != nil && !children.isEmpty {
        children.removeFirst()
      }
    
      // Do something with children
    })
    

提交回复
热议问题