表格视图不显示来自Firebase的评论或用户名

这里是我用来从firebase获取用户的评论和用户名的代码显示在我的tableview单元格的意见。 它目前不显示任何内容,但是当我发表评论时,我可以在firebase数据库中看到它。 我只需要读取所有的评论数据并显示它。

func fetchComment() { 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() guard let comDict = comPosted.value as? [String: AnyObject] else { continue } commentPosted.commentText = comDict["userComment"] as! String! commentPosted.username = comDict["userId"] as! String! self.comments.append(commentPosted) } }) } }) self.commentTableView.reloadData() ref.removeAllObservers() } 

Firebase是asynchronous的,因此代码需要允许Firebase时间从服务器返回数据。 该数据只在封闭内有效,封闭外的任何代码将在内部代码之前执行。 代码比互联网快得多!

所以在for循环之后移动tableView.reloadData将确保它在dataSource数组填充之后执行。

此外,代码中的两个观察事件是Single事件 – 意味着它们不保留附加到节点,所以removeAllObservers是多余的。

  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) } }) } }) 

上面的代码经过testing和工作,所以如果tableview仍然不显示数据,那么在tableView委托函数中可能会有问题。