我目前有一个tableview,您可以通过输入commentTextField来创建注释,然后将其保存到firebase,注释将显示在firebase中......我们也会在按下发送后的表格视图中显示注释...我唯一的问题是,当我退出tableview并返回评论消失时,它没有保存在tableview中......但它仍然出现在firebase中。以下是我向firebase和uitableview发送和保存数据的代码。
func loadData() {
ref.child("Comments").observeSingleEvent(of: .value, with: { (snapshot) in
self.messages.removeAll()
snapshot.children.forEach({ (child) in
if let obj = (child as? DataSnapshot)?.value as? [String : Any] {
if let author = obj["author"] as? String, let text = obj["text"] as? String {
let message = Message(author: author, comment: text)
self.messages.append(message)
}
}
})
self.chatTableViewController.reloadData()
})
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = chatTableViewController.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath) as! TableChatCell
let comment = messages[indexPath.row]
cell.usernameForChat.text = comment.author
cell.loadCommentToView.text = comment.comment
return cell
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
func tableViewDataLoad() {
chatTableViewController?.delegate = self
chatTableViewController?.dataSource = self
chatTableViewController?.reloadData()
}
@IBAction func handleSend(_ sender: Any) {
let ref = Database.database().reference().child("Comments")
let childRef = ref.childByAutoId()
if let author = Auth.auth().currentUser?.displayName, let text = commentTextField.text {
let values = ["author": author, "text": text]
let aMessage = Message(author: author, comment: text)
self.messages.append(aMessage)
chatTableViewController.reloadData()
childRef.updateChildValues(values)
}
}