首页 > 解决方案 > 如何知道在 swift 4 中实时 Firebase 的 childChanged 事件类型中更新了哪个子子项

问题描述

假设 My Firebase RealTime Database 的子名称 Users 还具有子子名称,例如“christianLiz@gmail.com”之类的电子邮件,则子子电子邮件还具有称为名称、年龄和国家/地区的子子名称。

我在 child 上添加了一个 observeEvent 改变了片段看起来像这样。

 ref.child("USERS").child("christianLiz@gmail,com").observe(.childChanged, with: { snapshot in

        if snapshot.exists(){
            let value = snapshot.value as? NSDictionary
            if value!["name"] != nil{
                print("here")
            }else{
                print("not here")
            }

    }){ (error) in
        print("")
    }

当我在更改国家/地区的值后进行测试时,应用程序崩溃并且原因是这个值![“名称”]。现在我知道 childChanged 事件仅返回在我的测试场景“国家”中更改的孩子,因此其他值不在快照中,但我想检查哪个是更新的名称或年龄或国家。我如何修改上面的代码来实现这一点。

标签: iosswiftfirebasefirebase-realtime-database

解决方案


用于hasChild检查孩子是否存在:

if snapshot.hasChild("country"){
      print("found")
    } else {
      print("not found")
}

推荐阅读