Home > Software engineering >  Firebase query ordering by child not working
Firebase query ordering by child not working

Time:06-04

I try to sort my table view content with creation date. The newest should be above. My code seems ok but it does not show the correct order. It is the opposite.

ref = Database.database().reference().child("placeID/\(placeIdFromSearch)")
ref.queryOrdered(byChild: "userTime").queryLimited(toLast: 10).observe(DataEventType.value, with: {(snapshot) in
    
    if snapshot.childrenCount > 0 {
        self.table.removeAll()
        
        for video in snapshot.children.allObjects as! [DataSnapshot] {
            
            let Object = video.value as? [String: AnyObject]
            
            let userName = Object?["userName"]
            let userGroup = Object?["userGroup"]
            let userComment = Object?["userComment"]
            let userTime = Object?["userTime"]
            let userLikes = Object?["userLikes"]
            
            let video = Videos(userName: userName as! String, userGroup: userGroup as! String, userComment: userComment as! String, userTime: userTime as! Int, userLikes: userLikes as! String)
            self.table.append(video)
            self.tableView.reloadData()
            
        }
    }    
})

enter image description here

CodePudding user response:

Firebase Realtime Database results are always in ascending order. There is no way to get them in descending order from the database, so you will have to reverse the results in your application code.

A simple option for this is to insert each item at the top of the table, instead of appending it to the bottom as you do now:

self.table.insert(video, at: 0)

The alternative would be to store inverted values in your database, like: userTime: -1654342137807. That way the ascending order that the database uses, will actually be what you want.

Also see:

  • Related