我在对firebase中的数据进行排序时遇到问题。我的代码的结果是完全无序的。我想在"日期"前订购。我已经尝试过使用.queryOrderedBy(child:"date"(,但我遇到了同样的问题。有人能帮我吗?
func getPosts(){
let ref = Database.database().reference()
ref.child("posts").queryOrderedByKey().observeSingleEvent(of: .value, with: { (snap) in
let postsSnap = snap.value as! [String : AnyObject]
for (_,post) in postsSnap {
let posst = Post()
if let author = post["author"] as? String, late date = post["date"], let postID = post["postID"] as? String, let userID = post["userID"] as? String {
posst.date = date
posst.author = author
posst.postID = postID
posst.userID = userID
self.posts.append(posst)
}
self.collectionview.reloadData()
}
})
}
我的Firebase数据库结构如下:
{
"posts" : {
"Optional("-M2tKGSlfsUng8XfmnbV")" : {
"author" : "Lilli",
"postID" : "-M2tKGSlfsUng8XfmnbV",
"date" : 1584731069721,
"userID" : "cayQLr27tsaJR76nH4H6yVUAOP03"
},
}
},
只需使用以下代码
self.posts.sort(by: {$0.date > $1.date})