如何按时间顺序对Firebase数据库进行排序?

时间:2017-02-28 21:22:43

标签: ios swift firebase firebase-realtime-database timestamp

我正在制作一个在帖子上发帖和评论的应用。但是,每当用户发布/评论时,他们就不会按照在UITableView中加载后发布的顺序显示。我已经在帖子和评论中实现了时间戳,但我无法弄清楚如何对它们进行排序。

我的数据库:

"posts" : {
   "47CCC57D-9056-4F5B-919E-F686065574A2" : {
     "comments" : {
        "99838A46-A84E-47E9-9D9C-E048543DC7C9" : {
          "comment" : "Would you trade for a red one?",
          "timestamp" : 1488315280579,
          "commentID" : "99838A46-A84E-47E9-9D9C-E048543DC7C9",
          "username" : "user"
        }
     },
     "description" : "Don't really need this anymore. Willing to go for less if I can get a trade",
     "image" : "JLMzSuhJmZ.jpeg",
     "postID" : "47CCC57D-9056-4F5B-919E-F686065574A2",
     "price" : "$5",
     "rating" : "8",
     "title" : "title",
     "uid" : "5U1TnNtkhegmcsrRt88Bs6AO4Gh2",
     "username" : "user"
},

我如何试图在CommentViewController中对评论进行排序:

var postDetails: String?
var posts = NSMutableArray()   

func loadData() {
   FIRDatabase.database().reference().child("posts").child(postDetails!)
              .child("comments").queryOrdered(byChild: "timestamp")
              .observeSingleEvent(of: .value, with: { snapshot in
                if let postsDictionary = snapshot.value as? [String: AnyObject] {
                    for post in postsDictionary {
                        self.posts.add(post.value)
                    }
                    self.tableView.reloadData()
                }
   })
}


 // Displays posts in postsDetailsTableView
 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
       let cell = tableView.dequeueReusableCell(withIdentifier: "commentCell", for: indexPath) as! CommentTableViewCell
       // Configure the cell...
       let post = self.posts[indexPath.row] as! [String: AnyObject]
       cell.selectionStyle = .none
       cell.commentLabel.text = post["comment"] as? String
       cell.usernameLabel.text = post["username"] as? String
       return cell
   }
}

我能做什么才能使每条评论按照发布的顺序进行?

1 个答案:

答案 0 :(得分:0)

问题:在您的代码中,您将返回快照,然后将其转换为无法排序的字典。

通过.value查询时,快照中包含有关排序的键,值和信息,但一旦快照转换为字典,排序就会丢失,因此您需要迭代子项以获得正确的顺序。

func loadData() {
   FIRDatabase.database().reference().child("posts").child(postDetails!)
              .child("comments").queryOrdered(byChild: "timestamp")
              .observe(.value, with: { snapshot in

               for child in snapshot.children {
                 print("child \(child)")
               }
   })
}