Swift Firebase sort by last 10 and then show 10 new values

末鹿安然 提交于 2020-01-17 05:41:27

问题


I am currently having trouble with displaying values through my tableview, as I am creating this Instagram/Facebook-like feed, where the tableView updates at the bottom(simply fetches new value from the database through firebase). However, I am really struggling with populating the tableView with non-dulpicate data. I am currently sorting my firebase ref by child (timestamp), and by default I display the "queryLimitedToLast(10)". However, here comes the problem. I can't really find a way to display "new" data, that has not been listed in the table view above.

I have a "curLength:Int = 10" in my ViewController (variable, obviously).

For each time the user updates the tableView, the curLength is += 10, followed by a function that simply updates the tableView. Unfortunately, I can't really figure out how to display non-existent data from the query, as I run it through "queryLimitedToLast(x)", which in this case just re-populates the tableView with the same data twice, and then 10 new records.

How would I approach this, if I wanted to display the latest data, "10 new posts" each update?


回答1:


You need to use your timestamps as pagination cursors. If you request 10 posts that are ordered by timestamp, query the next 10 posts starting at the value of the post with the most recent timestamp in your tableView. This way you will only fetch posts that are more recent than the most recent post you have.

// will give you posts before most recent timestamp
let beforeRef = FIRDatabase.database().referenceWithPath("posts")
    .queryOrderedByChild("timestamp")
    .queryEndingAtValue(mostRecentTimestamp - 1)
    .queryLimitedToLast(10)

// will give you posts after most recent timestamp
let afterRef = FIRDatabase.database().referenceWithPath("posts")
    .queryOrderedByChild("timestamp")
    .queryStartingAtValue(mostRecentTimestamp + 1)
    .queryLimitedToLast(10)

beforeRef.observeEventType(.ChildAdded, withBlock: { snap in
    print(snap) // prepend the snap to your datasource
})

afterRef.observeEventType(.ChildAdded, withBlock: { snap in
    print(snap) // append the snap to your datasource
})


来源:https://stackoverflow.com/questions/39421105/swift-firebase-sort-by-last-10-and-then-show-10-new-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!