当我将以下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
}
}
答案 0 :(得分:11)
当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})
答案 1 :(得分:1)
虽然我建议做一些发布的内容并创建一个类并按照这种方式进行,但我会给你另一种方法来进行排序。
由于您已经从Firebase按升序排序,并且您知道记录的数量,因此您可以这样做:
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])
}
答案 2 :(得分:0)
.reverse()
myRef.observe(.value) { (snapshot) in
guard var objects = snapshot.children.allObjects as? [DataSnapshot] else {
return
}
objects.reverse() //<========= HERE
//Now use your `objects`
...
}
答案 3 :(得分:0)
迅速5: 按必填字段排序后,将reversed()添加到对象中。 例如,假设您在FireStore的“天”字段中有一个月的某天。 这样的事情可以解决问题(在viewDidLoad中调用loadData()函数以查看输出):
let db = Firestore.firestore()
func loadData() {
db.collection("FireStoreCollectionName").order(by: "day").getDocuments { (querySnapshot, error) in
if let e = error {
print("There was an issue retrieving data from Firestore, \(e)")
} else {
for document in querySnapshot!.documents.reversed() {
let data = document.data()
let fDay = data["day"] as! Int
print(fDay)
}
}
}
}