2017-06-26 5 views
1

firebaseデータベースのエントリをセルの削除ボタンで削除しようとしていますが、データベースから削除できますが、テーブルビューに残っています。 Firebaseがデータベースを更新してテーブルのデータを正しく再ロードできるようになるまで、アプリケーションの実行を待機させる方法を理解してください。TableViewと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

あなたの現在のコードは、新しい子ノードが追加された場合、それが唯一のケースを扱う意味し、.childAddedイベントを観察します。また、子ノードが削除されたとき、あなたはあまりにも.childRemovedイベントを観察して処理する必要が処理するには

userRef.observe(.childRemoved, with: { (snapshot) in 
    // TODO: remove user from self.contacts and update table view 
関連する問題