swift - 值未从字典中删除

标签 swift firebase firebase-realtime-database swift-dictionary

我在 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

Screenshot

任何帮助将不胜感激,谢谢!

最佳答案

您只有数据的快照(副本)

从 firebase 数据库中删除该值; 试试这个:

//path should be like this (i guess):
let currentUserUid = FIRAuth.auth()!.c‌​urrentUser!.uid
ref.child("posts")
   .child(postId)
   .child("peopleWhoLike")
   .chi‌​ld(currentUserUid)
   .rem‌​oveValue()

或相同:

let currentUserUid = FIRAuth.auth()!.c‌​urrentUser!.uid
ref.child("posts/\(postId)/peopleWhoLike/\(currentUserUid)").rem‌​oveValue()

更新

如果您想删除个人 key - 那么您可以:

a) 迭代 peopleWhoLike 并查找是否是用户(但请将这个 let currentUserUid = FIRAuth.auth()!.c‌​urrentUser!.uid 放在循环之外!

//path should be like this (i guess):
let currentUserUid = FIRAuth.auth()!.c‌​urrentUser!.uid

// loop and when match `person.value == currentUserUid` then:
ref.child("posts")
   .child(postId)
   .child("peopleWhoLike")
   .chi‌​ld(person.key)  //<-- change here
   .rem‌​oveValue()

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/

相关文章:

ios - 从当前上下文中继续时缺少选项卡栏

swift - swift 2.0 中过滤方法的第二个参数

firebase - 在没有互联网连接的情况下使用 Firebase 模拟器

javascript - 使用身份验证安全规则时 Firebase 读取权限被拒绝

java - 当数据更改时,Firebase 不会检索最后的数据,并且不会以正确的方式执行 addValueEventListener 内的条件

JavaScript谷歌云函数: write Stripe values to Firebase

swift - 使用 IOKit 和 Swift 进行简单的键重映射

ios - Xcode 6.1 构建在设备上崩溃

Swift - Firebase 错误,如何访问第一个 child

javascript - 按 firebase 中的特定值检索数据