MHDev MHDev - 10 months ago 140
Swift Question

How can I delete a specific child node in Firebase from UITableViewCell using Swift

I have a

which looks like this image

this image.

When I swipe to delete the record, I can remove it perfectly okay from the array in which it is stored, but I am having difficulties in accessing it in Firebase to delete it there.

My Firebase database structure is as follows for the above screenshot:

bodyPart: "Arms"
exerciseName: "Test 1 "
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
bodyPart: "Chest"
exerciseName: "Test 2 "
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
bodyPart: "Legs"
exerciseName: "Test 3 "
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
bodyPart: "Arms"
exerciseName: "Test 4"
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"

How can I access the autoId value which is set when it is created e.g "-KWc7RTuOe5PefiMM2tL" so I can remove that child node?

Or alternatively could I access the
value depending on the
that is logged in?

Answer Source

Following on from what MHDev has already answered:

func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {

        if let exerciseName = exercises[indexPath.row].exerciseName {

            let ref = FIRDatabase.database().reference().child("userExercises")

            ref.queryOrdered(byChild: "exerciseName").queryEqual(toValue: exerciseName).observe(.childAdded, with: { (snapshot) in

                snapshot.ref.removeValue(completionBlock: { (error, reference) in
                    if error != nil {
                        print("There has been an error:\(error)")



        exercises.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .left)