Ios 同时从TableView和Firebase中删除行
我试图使用单元格上的delete按钮删除firebase数据库中的条目,我可以从数据库中删除它,但它仍保留在表视图中,我不知道如何将应用程序延迟到firebase更新数据库之后,以便正确重新加载表数据Ios 同时从TableView和Firebase中删除行,ios,uitableview,firebase,swift3,firebase-realtime-database,Ios,Uitableview,Firebase,Swift3,Firebase Realtime Database,我试图使用单元格上的delete按钮删除firebase数据库中的条目,我可以从数据库中删除它,但它仍保留在表视图中,我不知道如何将应用程序延迟到firebase更新数据库之后,以便正确重新加载表数据 var contacts = [Contact]() override func viewDidLoad() { contactsTable.delegate = self contactsTable.dataSource = self super.viewDidLoad
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
当前代码只观察
.childAdded
事件,这意味着它只处理添加新子节点时的情况
要在删除子节点时处理,还需要观察并处理.childRemoved
事件:
userRef.observe(.childRemoved, with: { (snapshot) in
// TODO: remove user from self.contacts and update table view