我需要按日期 (unix) 排列我的 firebase 数据。我认为 queryOrdered(byChild: "date")
可以解决问题。完成了 search并找到this这是有道理的:
But when you request the .value of the snapshot, the keys+data are converted to a Dictionary. Since a dictionary does not have an extra place to put the information about the order, that information is lost when converting to a dictionary.
使用相同的 json 但用 unix 日期修改...:
{
"users" : {
"alovelace" : {
"name" : "Last Year",
"date" : 1480550400
},
"eclarke" : {
"name" : "New Year Now",
"date" : 1483228800
},
"ghopper" : {
"name" : "New Year",
"date" : 1483228800
}
}
}
...当我的代码是这样的时候如何排序:
DataService.ds.REF_INCOMES.queryOrdered(byChild: "date").observe(.value, with: { (snapshot) in
if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot] {
print(snapshot)
for snap in snapshot {
if let incomeDict = snap.value as? [String: AnyObject] { // What needs to change here?
let key = snap.key
let income = Income(incomeId: key, incomeData: incomeDict)
self.incomes.append(income)
self.incomes.reverse()
}
}
}
self.tableView.reloadData()
})
下图,“去年”应该是最后但不是:
我有一个 ruby mentality所以我很快就迷路了。谢谢。
最佳答案
我想你在这里缺少的是 sort
功能,请尝试下面的代码,让我知道结果是什么:
DataService.ds.REF_INCOMES.queryOrdered(byChild: "date").observe(.value, with: { (snapshot) in
guard let usersSnapshot = snapshot.value as? [String:NSObject] else{
return
}
let users = usersSnapshot["users"] as! [String:AnyObject]
let sorted = users.sorted{($0.0.value["date"] as! Double) > ($0.1.value["date"] as! Double)}
print(sorted) // It should be: New Year Now, New Year, Last Year
})
关于ios - 使用 queryOrdered by date 对 Firebase 数据进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41416359/