如何使用 Swift 从 UITableViewCell 中删除 Firebase 中的特定子节点 [英] How can I delete a specific child node in Firebase from UITableViewCell using Swift
问题描述
我有一个 UITableView
看起来像这张图片
I have a UITableView
which looks like this image
.
当我滑动删除记录时,我可以从存储它的数组中完全删除它,但我在 Firebase 中访问它以在那里删除它时遇到困难.
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.
对于上面的截图,我的 Firebase 数据库结构如下:
My Firebase database structure is as follows for the above screenshot:
-KWc7RTuOe5PefiMM2tL
bodyPart: "Arms"
exerciseName: "Test 1 "
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
-KWcEbpw_f6kxcePY5cO
bodyPart: "Chest"
exerciseName: "Test 2 "
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
-KWcEdUN49QaJIVf0kwO
bodyPart: "Legs"
exerciseName: "Test 3 "
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
-KWcFrMSaLKQRxghGHyT
bodyPart: "Arms"
exerciseName: "Test 4"
userId: "8rHmyTxdocTEvk1ERiiavjMUYyD3"
如何访问创建时设置的 autoId 值,例如-KWc7RTuOe5PefiMM2tL",以便删除该子节点?
How can I access the autoId value which is set when it is created e.g "-KWc7RTuOe5PefiMM2tL" so I can remove that child node?
或者我可以根据登录的 UserId
访问 exerciseName
值吗?
Or alternatively could I access the exerciseName
value depending on the UserId
that is logged in?
推荐答案
根据 MHDev 已经回答的内容:
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)
}
}
这篇关于如何使用 Swift 从 UITableViewCell 中删除 Firebase 中的特定子节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!