load tableView基于最新的时间戳

时间:2017-05-14 00:26:55

标签: swift uitableview firebase-realtime-database firebase-authentication

我想根据Firebase中的timestamp子值对tableView进行排序。我希望每次tableView加载(或重新加载)时,添加到tableView的最新tableViewCell都会放在tableview的顶部。感谢您提前提供任何帮助!

//来自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)

    }

1 个答案:

答案 0 :(得分:1)

如果您只想将最新的数据记录插入阵列的第一个索引中。为什么不做这样的事情:

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