我在 Firebase 中有一个名为 peopleWhoLike
的字典,键是自动 ID,值是喜欢的用户的 uid,我正在尝试循环访问 peopleWhoLike
字典并找到以当前用户 uid 作为值的条目,以便我可以删除它,但该值没有被删除。
func removeLike(postID: String){
ref.child("posts").child(postID).observe(.value, with: { (snapshot) in
if let info = snapshot.value as? [String : AnyObject]{
if var peopleWhoLike = info["peopleWhoLike"] as? [String : String]{
print("peopleWhoLike - \(peopleWhoLike)")
for person in peopleWhoLike{
if person.value == FIRAuth.auth()!.currentUser!.uid{
peopleWhoLike.removeValue(forKey: person.key)
print("personkey - \(person.key)")
}
}
}
}
})
}
两个打印语句都正确打印,即 person.key
是正确的 key
任何帮助将不胜感激,谢谢!
最佳答案
您只有数据的快照(副本)
从 firebase 数据库中删除该值; 试试这个:
//path should be like this (i guess):
let currentUserUid = FIRAuth.auth()!.currentUser!.uid
ref.child("posts")
.child(postId)
.child("peopleWhoLike")
.child(currentUserUid)
.removeValue()
或相同:
let currentUserUid = FIRAuth.auth()!.currentUser!.uid
ref.child("posts/\(postId)/peopleWhoLike/\(currentUserUid)").removeValue()
更新
如果您想删除个人 key - 那么您可以:
a) 迭代 peopleWhoLike 并查找是否是用户(但请将这个 let currentUserUid = FIRAuth.auth()!.currentUser!.uid
放在循环之外!
//path should be like this (i guess):
let currentUserUid = FIRAuth.auth()!.currentUser!.uid
// loop and when match `person.value == currentUserUid` then:
ref.child("posts")
.child(postId)
.child("peopleWhoLike")
.child(person.key) //<-- change here
.removeValue()
b) 您在查询中进行搜索。然后删除生成的节点。
ref.child("posts")
.child(postId)
.child("peopleWhoLike")
.startAt(currentUserId)
.endAt(currentUserId)
. [...] do something
我不知道此时是否可以直接调用.removeValue()
。但使用 SingleEvent 和快照,您可以执行 snapshot.ref.removeValue()
- 在删除之前仔细检查。但由于这会产生引用,您应该能够直接调用 .removeValue()
ref.child("posts")
.child(postId)
.child("peopleWhoLike")
.startAt(currentUserId)
.endAt(currentUserId)
.removeValue()
注意:此搜索比直接路径花费更长的时间
请参阅此处的文档进行查询:
https://firebase.googleblog.com/2013/10/queries-part-1-common-sql-queries.html#byemail
https://firebase.google.com/docs/database/ios/read-and-write#delete_data
注意:
我建议您使用userUid
作为键保存它,因为您只需要一个在线用户即可删除(请参阅我的第一个代码片段,您不需要从peopleWhoLike
获取所有数据code>),值仅为 1,或者您可以保存当前日期(然后您就知道它何时被喜欢)
关于swift - 值未从字典中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41910462/