一尘不染

Firebase查询排序顺序迅速?

swift

当我将以下Firebase数据库数据加载到tableView中时,数据按日期升序排序。如何通过降序排序(在顶部显示最新帖子)?

在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"
    },

谢谢!!

编辑:下面的代码是整个解决方案,感谢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
    }
}

阅读 287

收藏
2020-07-07

共1个答案

一尘不染

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

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

Swift 3版本:

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

Swift 4版本:

yourDataArray.sort(by: {$0.date > $1.date})
2020-07-07