[英]Deleting a row from a TableView and Firebase simultaneously
我試圖使用單元格上的刪除按鈕刪除firebase數據庫中的條目,我可以從數據庫中刪除它,但它仍然保留在表格視圖中,我無法弄清楚如何延遲應用程序等到Firebase之后更新數據庫,以便我可以正確地重新加載表數據。
var contacts = [Contact]()
override func viewDidLoad() {
contactsTable.delegate = self
contactsTable.dataSource = self
super.viewDidLoad()
fetchContacts(){
self.contactsTable.reloadData()
}
}
func fetchContacts(completion: @escaping () -> ()){
contacts = [Contact]()
let userRef = FIRDatabase.database().reference()
userRef.observe(.childAdded, with: { (snapshot) in
print(snapshot)
if let dictionary = snapshot.value as? [String: AnyObject]{
let contact = Contact()
contact.setValuesForKeys(dictionary)
self.contacts.append(contact)
}
completion()
}, withCancel: nil)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:ContactCell = self.contactsTable.dequeueReusableCell(withIdentifier: "contactCell") as! ContactCell
cell.tapTrashAction = { [weak self] (cell) in
let alert = UIAlertController(title: "Confirm", message: "Are you sure you want to delete \(contactName!) as a contact?", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Delete", style: UIAlertActionStyle.destructive, handler:{ action in
self!.handleDelete(phone: phoneNumber!)
//self?.contactsTable.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
}))
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: nil))
self?.present(alert, animated: true, completion: nil)
}
return cell
}
func handleDelete(phone: String){
let userRef = FIRDatabase.database().reference()
userRef.child(phone).removeValue { (error, ref) in
if error != nil {
print("Error: \(error)")
}
self.fetchContacts(){
self.contactsTable.reloadData()
}
}
}
您當前的代碼僅觀察.childAdded
事件,這意味着它僅處理添加新子節點時的情況。
要在刪除子節點時進行處理,還需要觀察並處理.childRemoved
事件:
userRef.observe(.childRemoved, with: { (snapshot) in
// TODO: remove user from self.contacts and update table view
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.