加载表基于最新时间戳查看



我想根据 Firebase 中的时间戳子值对表视图进行排序。我希望每次加载(或重新加载(表视图时,将添加到表视图的最新表视图单元格放在表视图的顶部。提前感谢您的任何帮助!

来自 Firebase 的 JSON

{
  "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()

最新更新