2016-08-04 27 views
2

当我将以下Firebase数据库数据加载到我的tableView中时,数据按日期升序排序。我怎样才能以降序排列(显示最上面的帖子)?在swift中的Firebase查询排序顺序?

查询在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 
    } 
} 
+1

您使用queryOrderedByChild的意思是你期待的数据被那为什么预购你是手动排序吗? –

+1

您正在重载'cellForRowAtIndexPath'中的表格视图!这将在崩溃中结束! –

回答

9

当火力地堡将数据加载到您的tableView数据源阵列,称之为:

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

斯威夫特3版本:

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

感谢您的回复!我得到错误'类型'FIRDataSnapshot'的值没有成员'date''。更新了我的代码 – winston

+0

啊好的。这是我的建议。创建一个名为Post的新自定义类(应该不超过5分钟),其属性为“date”,“postingBy”和“status”。您的self.posts数组将成为Post对象的数组,然后排序数组就没有问题。虽然看起来有很多工作要做,但将自定义类与Firebase数据对象关联起来会让您的生活更轻松,尤其是在路上。 – Bawpotter

+0

我用新的Post类更新了这个问题。我使用Firebase文档中的一些示例代码作为参考。我现在该如何指出我的self.posts数组来查看这个新类? – winston

1

虽然我不建议做什么被张贴和创建一个类,并以这种方式,我会给你另一种方式来做排序。

既然你已经把它从火力地堡升序排序,你知道的记录数,你可以这样做:

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]) 
}