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
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.