首页 > 解决方案 > how to iterate and append Firebase data

问题描述

I have a table view that prints out comments.

    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 {
                for post in postsDictionary {
                    //main comments
                    self.Comments.add(post.value)
                }
                DispatchQueue.main.async(execute: {
                    self.TableView.reloadData()
                })
            }
        }
    })

For every post available I want to look to see if it has a comment associated with it (nested comment) and if it does, append it to comments array.

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 {
            // nested comments
            self.Comments.add(post.value)
        }
        DispatchQueue.main.async(execute: {
            self.TableView.reloadData()
        })
    }
})

This is the attempted code to get the nested comments/ This is the pathway to get the nested comments. This is also what my JSON looks like.

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",

}}

标签: swiftxcodeuitableviewfirebasefirebase-realtime-database

解决方案


推荐阅读