I have a UITableView
which looks like this image
.
When I swipe to delete th
It's a fairly straightforward process:
In general, a datasource for tableViews is an array. That array is built from dictionaries read from Firebase snapshots - or an array of objects built from the snapshots (recommended).
So here's an example that matches your Firebase structure (this was populated from a single node from a snapshot)
class Exercise {
key: "KWc7RTuOe5PefiMM2tL"
bodyPart: "Legs"
exerciseName: "Test 3 "
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
}
Then, when the user swipes row 3 for example, retrieve the Exercise object from the array, row3.
let theObject = ExerciseArray[3]
let parentNode = theObject.key
let ref = rootNode.child(parentNode)
ref.setValue(nil)
and you're done.
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)
}
}
To solve this issue I tried a number of different methods before finally reaching my intended result.
To delete the value, I created a reference to the child node 'userExercises', then ordered it by 'exerciseName' and then .queryEqual(toValue:) the exercise name value which I extracted form the UITableViewCell.
I then removed the snapshot value of this and the example code is below:
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)
}
}