我正在尝试使用单元格上的删除按钮删除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()
}
}
}
答案 0 :(得分:0)
您当前的代码仅观察.childAdded
个事件,这意味着它只处理添加新子节点时的情况。
要处理删除子节点的时间,您还需要观察并处理.childRemoved
事件:
userRef.observe(.childRemoved, with: { (snapshot) in
// TODO: remove user from self.contacts and update table view