Firebase在swift中查询sorting顺序?

当我将以下Firebase数据库数据加载到我的tableView中时,数据按date升序sorting。 我怎样才能降序(显示最新的post在顶部)?

在Xcode中查询:

let ref = self.rootRef.child("posts").queryOrderedByChild("date").observeEventType(.ChildAdded, withBlock: { (snapshot) -> Void in 

JSON导出:

 "posts" : { "-KMFYKt7rmfZINetx1hF" : { "date" : "07/09/16 12:46 PM", "postedBy" : "sJUCytVIWmX7CgmrypqNai8vGBg2", "status" : "test" }, "-KMFYZeJmgvmnqZ4OhT_" : { "date" : "07/09/16 12:47 PM", "postedBy" : "sJUCytVIWmX7CgmrypqNai8vGBg2", "status" : "test" }, 

谢谢!!

编辑:下面的代码是整个解决scheme,由于Bawpotter

更新的查询:

 let ref = self.rootRef.child("posts").queryOrderedByChild("date").observeEventType(.ChildAdded, withBlock: { (snapshot) -> Void in let post = Post.init(key: snapshot.key, date: snapshot.value!["date"] as! String, postedBy: snapshot.value!["postedBy"] as! String, status: snapshot.value!["status"] as! String) self.posts.append(post) self.tableView.insertRowsAtIndexPaths([NSIndexPath(forRow: self.posts.count-1, inSection: 0)], withRowAnimation: .Automatic) 

tableView cellForRowAtIndexPath

 override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("PostCell", forIndexPath: indexPath) as! PostCell self.posts.sortInPlace({$0.date > $1.date}) self.tableView.reloadData() 

Post.swift:

 import UIKit class Post { var key: String var date: String var postedBy: String var status: String init(key: String, date: String, postedBy: String, status: String){ self.key = key self.date = date self.postedBy = postedBy self.status = status } } 

当Firebase将数据加载到您的tableView数据源数组中时,请调用以下命令:

yourDataArray.sortInPlace({$0.date > $1.date})

Swift 3版本:

 yourDataArray.sort({$0.date > $1.date}) 

虽然我build议做什么张贴和创build一个类,并这样做,我会给你另一种方法来做sorting。

由于您已经按照Firebase的升序sorting,并且您知道logging数量,因此您可以这样做:

 guard let value = snapshot.children.allObjects as? [FIRDataSnapshot] else { return } var valueSorted: [FIRDataSnapshot] = [FIRDataSnapshot]() var i: Int = value.count while i > 0 { i = i - 1 valueSorted.append(value[i]) }