Swift 基于最新时间戳加载tableView
我想根据Firebase中的timestamp子值对tableView进行排序。我希望在每次加载(或重新加载)tableView时,将添加到tableView的最新tableViewCell放置在tableView的顶部。提前谢谢你的帮助 //来自firebase的JSONSwift 基于最新时间戳加载tableView,swift,uitableview,firebase-realtime-database,firebase-authentication,Swift,Uitableview,Firebase Realtime Database,Firebase Authentication,我想根据Firebase中的timestamp子值对tableView进行排序。我希望在每次加载(或重新加载)tableView时,将添加到tableView的最新tableViewCell放置在tableView的顶部。提前谢谢你的帮助 //来自firebase的JSON { "users" : { "CmtuebwVrmOG3n4uSsIK1b4FsSN2" : { "Places" : { "-KhDwZJvca9HedFluJ5O" : {
{
"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
}
},
//用于加载位置表视图的函数
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)
}
如果只想将最新的数据记录插入数组的第一个索引中。你为什么不这样做:
self.placeList.insert(place, at: 0)
而不是
self.placeList.append(place)
顺便说一句,我不认为以下是必要的:
self.tableView.beginUpdates()
self.tableView.insertRows(at: [IndexPath(row: self.placeList.count-1, section: 0)], with: .automatic)
self.tableView.endUpdates()
谢谢是-开始和结束更新代码对我来说似乎也是多余的。不用担心,如果它解决了您的问题,请将您的问题标记为已回答