Ios 删除tableView单元格并从firebase中删除数据
我正在从事社交网络的研究项目。停留在从Firebase数据库删除用户评论的阶段。要删除特定的注释,我需要知道注释Id,但我不知道如何访问它。我真的很感谢你在这方面的帮助 Firebase数据库示例: 评论视图控制器:Ios 删除tableView单元格并从firebase中删除数据,ios,swift,firebase,firebase-realtime-database,Ios,Swift,Firebase,Firebase Realtime Database,我正在从事社交网络的研究项目。停留在从Firebase数据库删除用户评论的阶段。要删除特定的注释,我需要知道注释Id,但我不知道如何访问它。我真的很感谢你在这方面的帮助 Firebase数据库示例: 评论视图控制器: class CommentViewController: UIViewController { @IBOutlet weak var sendButton: UIButton! @IBOutlet weak var commentTextField: UITextField!
class CommentViewController: UIViewController {
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var commentTextField: UITextField!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var constraintToBottom: NSLayoutConstraint!
var postId: String!
var comments = [Comment]()
var users = [User]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
title = "Comment"
tableView.estimatedRowHeight = 77
tableView.rowHeight = UITableView.automaticDimension
empty()
handleTextField()
loadComments()
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow(_:)), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide(_:)), name: UIResponder.keyboardWillHideNotification, object: nil)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.endEditing(true)
}
@objc func keyboardWillShow(_ notification: NSNotification) {
let keyboardFrame = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as AnyObject).cgRectValue
UIView.animate(withDuration: 0.3) {
self.constraintToBottom.constant = keyboardFrame!.height
self.view.layoutIfNeeded()
}
}
@objc func keyboardWillHide(_ notification: NSNotification) {
UIView.animate(withDuration: 0.3) {
self.constraintToBottom.constant = 0
self.view.layoutIfNeeded()
}
}
var comment: Comment?
func loadComments() {
Api.Post_Comment.REF_POST_COMMENTS.child(self.postId).observe(.childAdded, with: {
snapshot in
Api.Comment.observeComments(withPostId: snapshot.key, completion: {
comment in
self.fetchUser(uid: comment.uid!, completed: {
self.comments.append(comment)
self.tableView.reloadData()
})
})
})
}
func fetchUser(uid: String, completed: @escaping() -> Void ) {
Api.User.observeUser(withId: uid, completion: {
user in
self.users.append(user)
completed()
})
}
func handleTextField() {
commentTextField.addTarget(self, action: #selector(self.textFieldDidChange), for: UIControl.Event.editingChanged)
}
@objc func textFieldDidChange() {
if let commentText = commentTextField.text, !commentText.isEmpty {
sendButton.setTitleColor(UIColor.black, for: UIControl.State.normal)
sendButton.isEnabled = true
return
}
sendButton.setTitleColor(UIColor.lightGray, for: UIControl.State.normal)
sendButton.isEnabled = false
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.tabBar.isHidden = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.tabBarController?.tabBar.isHidden = false
}
@IBAction func sendButton_TouchUpInside(_ sender: Any) {
let commentsReference = Api.Comment.REF_COMMENTS
let newCommentId = commentsReference.childByAutoId().key!
let newCommentReference = commentsReference.child(newCommentId)
guard let currentUser = Api.User.CURRENT_USER else {
return
}
let currentUserId = currentUser.uid
newCommentReference.setValue(["uid": currentUserId, "commentText": commentTextField.text!], withCompletionBlock: {
(error, ref) in
if error != nil {
ProgressHUD.showError(error!.localizedDescription)
return
}
let postCommentRef = Api.Post_Comment.REF_POST_COMMENTS.child(self.postId).child(newCommentId)
postCommentRef.setValue(true, withCompletionBlock: { (error, ref) in
if error != nil {
ProgressHUD.showError(error!.localizedDescription)
return
}
})
self.empty()
self.view.endEditing(true)
})
}
func empty() {
self.commentTextField.text = ""
sendButton.setTitleColor(UIColor.lightGray, for: UIControl.State.normal)
sendButton.isEnabled = false
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Comment_ProfileSegue" {
let profileVC = segue.destination as! ProfileUserViewController
let userId = sender as! String
profileVC.userId = userId
}
}
extension CommentViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return comments.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CommentCell", for: indexPath) as! CommentTableViewCell
let comment = comments[indexPath.row]
let user = users[indexPath.row]
cell.comment = comment
cell.user = user
cell.delegate = self
return cell
}
func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if (editingStyle == .delete) {
}
}
注释Api
class CommentApi {
var REF_COMMENTS = Database.database().reference().child("comments")
func observeComments(withPostId id: String, completion: @escaping (Comment) -> Void) {
REF_COMMENTS.child(id).observeSingleEvent(of: .value, with: {
snapshot in
if let dict = snapshot.value as? [String: Any] {
let newComment = Comment.transformComment(dict: dict, key: snapshot.key)
completion(newComment)
}
})
}
func observeComment(withId id: String, completion: @escaping (Comment) -> Void) {
REF_COMMENTS.child(id).observeSingleEvent(of: DataEventType.value, with: {
snapshot in
if let dict = snapshot.value as? [String: Any] {
let comment = Comment.transformComment(dict: dict, key: snapshot.key)
completion(comment)
}
})
}
注释模型:
class Comment {
var commentText: String?
var uid: String?
var id: String?}
extension Comment {
static func transformComment(dict: [String: Any], key: String) -> Comment {
let comment = Comment()
comment.id = key
comment.commentText = dict["commentText"] as? String
comment.uid = dict["uid"] as? String
return comment
}
从高层来说,tableView由一个数据源支持,通常是一个数组,它是tableView中显示内容的源
var userCommentArray = [UserComment]()
您应该从Firebase加载数据,并将该数据作为UserComment对象存储在数组中
class UserComment {
var firebaseKey = ""
var commentText = ""
var uid = ""
}
firebase_key属性是firebase中节点的密钥,在屏幕截图中显示为-MH_xxxx
,然后commentText和uid是该节点的子数据
数组中元素的索引与tableView中显示的内容匹配,因此行0与数组索引0匹配,行1与数组索引1匹配,等等
当用户删除行1时,您知道这是数组中的索引1。读取对象,获取它的firebaseKey,然后从firebase中删除它,相应地更新数组,然后重新加载UI
有关该过程的详细信息,请参阅我对您的答复。我认为您应该重新构建firebase数据库,以便在帖子中可以找到使用ID对该帖子发表评论的用户。当您要删除特定评论时,请使用用户ID访问帖子中的评论,然后轻松删除您想要的评论。
class UserComment {
var firebaseKey = ""
var commentText = ""
var uid = ""
}