由firebase子组织tableview单元格

时间:2018-07-17 03:48:07

标签: arrays swift xcode firebase firebase-realtime-database

我想在评论区添加类似于instagram的内容。用户可以在其中发表评论,其他用户可以在评论中发表评论。像这样: enter image description here

在我的Firebase数据库中,注释非常嵌套。

post-1069: {
    "comment-487" : {
      "id" : "comment-487",
      "content" : "blah blah blah",
      "comments" : {
        "comment-489" : {
          "id" : "comment-489",
          "content" : "i love you",
          "post_id" : "post-1069",
          "reply_to" : "comment-487",
        },
        "comment-490" : {
          "id" : "comment-490",
          "content" : "help me",
           "post_id" : "post-1069",
          "reply_to" : "comment-487",

}}

到目前为止,通过执行以下操作,我可以输出属于某个帖子的所有评论:

 func loadComments(){
    Database.database().reference().child("main").child("posts").child(postID!).child("comments").queryOrdered(byChild: "id").observeSingleEvent(of: .value, with: { (snapshot:DataSnapshot) in

            if let postsDictionary = snapshot .value as? [String: AnyObject] {

                  for testingkey in postsDictionary.keys {
                    Database.database().reference().child("main").child("posts").child(self.postID!).child("comments").child(testingkey).child("comments").queryOrdered(byChild: "post_id").observeSingleEvent(of: .value, with: { (snapshot:DataSnapshot) in

                         if let postsDictionary = snapshot .value as? [String: AnyObject] {

                            for post in postsDictionary {

                                self.Comments.add(post.value)
                            }
                            self.TableView.reloadData()
                        }


                    })
                }


                for post in postsDictionary {

                    self.Comments.add(post.value)

                }

                self.TableView.reloadData()

            }})

       print(self.Comments)
    }
     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    // Configure the cell...

    let cell = tableView.dequeueReusableCell(withIdentifier: "Main", for: indexPath) as! PostTableViewCell

    //Configure the cell

    let post = Comments[indexPath.row] as! [String: AnyObject]


    cell.comment.text = post["content"] as? String


    replyId = post["id"] as? String

    let replyTo = post["reply_to"] as? String
    let postID = post["post_id"] as? String



    if replyTo == postID {

    } else {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Reply", for: indexPath) as! RepliesTableViewCell


        let post = Comments[indexPath.row] as! [String: AnyObject]

        cell.ReplyText.text = post["content"] as? String

        return cell
    }



    return cell

}

我很难对评论进行排序,以便将评论的评论打印在其指定的评论下。到目前为止,似乎有两个不同的数组,我不确定如何将其转换为一个数组,以便我可以操纵单元并按需要的方式组织它。

0 个答案:

没有答案