Kaiser Abliz Kaiser Abliz - 27 days ago 8
iOS Question

How do I do queryOrdered(bychild) for this?

I have set up my firebase as in the picture, Now I would like to feed my posts with only new posts by comparing each post timestamp, I have written the code below

func getRecentPosts(start timestamp: Int? = nil, limit: UInt, completionHandler: @escaping (([Post]) -> Void)){

let POST_DB_REF: DatabaseReference = Database.database().reference().child("posts")
var allPosts = POST_DB_REF.queryOrdered(byChild: "timestamp")

if let latestPostTimestamp = timestamp, latestPostTimestamp > 0 {
//If the timestamp is specified, we will get the posts with timestamp newer than the given value
allPosts = allPosts.queryStarting(atValue: latestPostTimestamp + 1, childKey: Post.PostInfoKey.timestamp).queryLimited(toLast: limit)
} else {
//Otherwise, we will just get the most recent posts
allPosts = allPosts.queryLimited(toLast: limit)

//Call Firebase API to retrieve the latest records
allPosts.observeSingleEvent(of: .value, with: { (snapshot) in
var newPosts: [Post] = []
for userPosts in snapshot.children.allObjects as! [DataSnapshot] {
for eachPost in userPosts.children.allObjects as! [DataSnapshot] {
let postInfo = eachPost.value as? [String:Any] ?? [:]
if let post = Post(postId: eachPost.key, postInfo: postInfo) {

if newPosts.count > 0 {
//Order in descending order (i.e. the latest post becomes the first post)
newPosts.sort(by: {$0.timestamp > $1.timestamp})

Here is my firebase config.
This works with the first run, then if I post a new feed it does not get updated, any Ideas ?
Thanks in advance.

Answer Source

When you're using allPosts.observeSingleEvent, you will always get the value from the local Firebase cache. If you always need the latest value from the server, you must use allPosts.observe instead which will fire events as soon as the value on the server has changed.

Another option is to disable the cache:

Database.database().isPersistenceEnabled = false