【问题标题】:Deleting a row from a TableView and Firebase simultaneously同时从 TableView 和 Firebase 中删除一行
【发布时间】:2017-11-29 15:46:46
【问题描述】:

我正在尝试使用单元格上的删除按钮删除 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()
        }
    }
}

【问题讨论】:

    标签: ios uitableview firebase swift3 firebase-realtime-database


    【解决方案1】:

    您当前的代码只观察.childAdded 事件,这意味着它只处理添加新子节点时的情况。

    要同时处理子节点被删除的情况,还需要观察并处理.childRemoved事件:

    userRef.observe(.childRemoved, with: { (snapshot) in
        // TODO: remove user from self.contacts and update table view
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-15
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多