Table view is not displaying the comments or username from Firebase

前端 未结 1 1347
小蘑菇
小蘑菇 2020-12-22 14:25

Here\'s the code I use to fetch the comments and username of users from firebase to display in my tableview cell for comments. It currently does not display anything but whe

相关标签:
1条回答
  • 2020-12-22 14:36

    Firebase is asynchronous and therefore the code needs to allow Firebase time to return the data from the server. That data is only valid inside the closure and any code outside the closure will execute before the code inside. Code is much faster than the internet!

    So moving the tableView.reloadData right after the for loop will ensure it executes after the dataSource array is populated.

    Also, the two observe events in the code are Single events - meaning they don't stay attached to the node so the removeAllObservers is extraneous.

        let ref = FIRDatabase.database().reference().child("Newsfeed")
                             .child(itemSelected.title)
    
        ref.observeSingleEvent(of: .value, with: { snapshot in
            if snapshot.hasChild("comments")
            {
                ref.child("comments").observeSingleEvent(of: .value, with: {snappy in
                    for comPosted in snappy.children.allObjects as! [FIRDataSnapshot]
                    {
                        let commentPosted = comment()
                        let comDict = comPosted.value as! [String: AnyObject]
                        commentPosted.commentText = comDict["userComment"] as! String!
                        commentPosted.username = comDict["userId"] as! String!
                        self.comments.append(commentPosted)
                    }
                    self.commentTableView.reloadData()
    
                    //A quick check to ensure the array is populated.
                    //Can be removed.
                    for c in self.comments {
                        print(c.commentText)
                        print(c.username)
                    }  
                })
            }
        })
    

    The above code is tested and works so if the tableview is still not displaying the data, there may be an issue in the tableView delegate functions.

    0 讨论(0)
提交回复
热议问题