2

I want to refresh my conversations (table view cells) after deleting a conversation through a swipe action sheet.

I tried to reload the table view after deleting the data but it doesn't work. Also with a async.

 // Swipe Action Sheet solution
func tableView(_ tableView: UITableView,
               trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration?
{

    // Write action code for the Flag
    let deleteAction = UIContextualAction(style: .normal, title:  "Löschen", handler: { (ac:UIContextualAction, view:UIView, success:(Bool) -> Void) in
        let ref = Database.database().reference()
        ref.child("users").child((self.currentUser?.uid)!).child("conversations").child((self.items[indexPath.row].user.uid)!).removeValue()
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
        success(true)
    })
    deleteAction.backgroundColor = .red
    return UISwipeActionsConfiguration(actions: [deleteAction])

}

Thanks in advance for your help!

jo1995
  • 414
  • 1
  • 5
  • 14

2 Answers2

1

You have to reload data in completion block of removeValue method if there isn't any error. Also before you reload data you have to remove item from items array

.removeValue { error,_ in
    if error == nil {
        self.items.remove(at: indexPath.row)
        self.tableView.reloadData() // self.tableView.deleteRows(at: [indexPath], with: .automatic)
    }
    success(error == nil)
}
Robert Dresler
  • 10,580
  • 2
  • 22
  • 40
  • Is this completion block being called on the main queue? If not, be sure you force the UI update to be on the main queue. – rmaddy Dec 20 '18 at 16:32
  • @rmaddy https://stackoverflow.com/a/39183023/10253094 but I'm not sure, is that this case? – Robert Dresler Dec 20 '18 at 17:05
  • @rmaddy I also didn't find anything about it here: https://firebase.google.com/docs/reference/ios/firebasedatabase/api/reference/Classes/FIRDatabaseReference#/c:objc(cs)FIRDatabaseReference(im)removeValueWithCompletionBlock: – Robert Dresler Dec 20 '18 at 17:10
0

To delete row using swipe, you can use

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            items.remove(at: indexPath.row)
            tableView.deleteRows(at: [indexPath], with: .fade)
        } 
    }

func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {

    return true
}

And because you not reload table view, that will look much better

canister_exister
  • 567
  • 4
  • 15