Reputation: 1259
I would like to sort a tableView based on the timestamp child value in Firebase. I would like the newest tableViewCell added to the tableView to be placed on top of the tableview every time the tableView loads (or reloads). Thanks for any help in advance!
// JSON from firebase
{
"users" : {
"CmtuebwVrmOG3n4uSsIK1b4FsSN2" : {
"Places" : {
"-KhDwZJvca9HedFluJ5O" : {
"addedBy" : "CmtuebwVrmOG3n4uSsIK1b4FsSN2",
"place" : "Edinburgh, UK",
"timestamp" : 1.491678152020824E9
},
"-KhE7raDrM2RRs-N6FXg" : {
"addedBy" : "CmtuebwVrmOG3n4uSsIK1b4FsSN2",
"place" : "Hong Kong",
"timestamp" : 1.49168137667081E9
},
"-KhFUaEjjhE3RBOw95fc" : {
"addedBy" : "CmtuebwVrmOG3n4uSsIK1b4FsSN2",
"place" : "Illinois, USA",
"timestamp" : 1.491704112134812E9
},
"-KhzSIHrFHiUEBrzBKUH" : {
"addedBy" : "CmtuebwVrmOG3n4uSsIK1b4FsSN2",
"place" : "Ghana",
"timestamp" : 1.492492039376661E9
}
},
// function to load tableview of places
var placeList = [Place]()
var placesDictionary = [String: Place]()
func fetchPlaces() {
let uid = FIRAuth.auth()?.currentUser?.uid
let ref = FIRDatabase.database().reference().child("users").child(uid!).child("Places")
ref.observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let place = Place()
place.setValuesForKeys(dictionary)
// self.placeList.append(place)
if let addedBy = place.addedBy {
self.placesDictionary[addedBy] = place
self.placeList.append(place)
self.tableView.beginUpdates()
self.tableView.insertRows(at: [IndexPath(row: self.placeList.count-1, section: 0)], with: .automatic)
self.tableView.endUpdates()
}
//this will crash because of background thread, so lets call this on dispatch_async main thread
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
})
}
}, withCancel: nil)
}
Upvotes: 1
Views: 85
Reputation: 3499
If you just want the latest data record to be inserted into the 1st index of your array. Why don't you do something like this:
self.placeList.insert(place, at: 0)
rather than
self.placeList.append(place)
Btw, I don't think the following would be necessary:
self.tableView.beginUpdates()
self.tableView.insertRows(at: [IndexPath(row: self.placeList.count-1, section: 0)], with: .automatic)
self.tableView.endUpdates()
Upvotes: 2