使用Swift在Firebase中遍历嵌套的快照子项 [英] Iterate through nested snapshot children in Firebase using Swift

查看:110
本文介绍了使用Swift在Firebase中遍历嵌套的快照子项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的数据库是这样构建的:

 Users:{
用户名:{
收藏夹:{
Location:{
Latitude:123,
LocationName:旧金山,
经度:123
},
Location2:{
Latitude:123,
LocationName:London,
Longitude:123
}
}
}
}

我试图打印出所有的LocationName键,并且能够打印这个键的一个实例,但是无法循环并打印此密钥的所有实例。



我不知道在我的for循环中哪里出错了?



与下面的工作。

  FIRApp.configure()

let databaseRef = FIRDatabase.database()。reference()。 child(Users)。child(Username)。child(Favorites)


let databaseHandle = databaseRef.observe(.value,其中:{(snapshot)in $

如果让dbLocation = snapshot.childSnapshot(forPath:LocationName)as?String {

print(dbLocation)

$ b print(item)

}

})

我对Swift非常陌生,甚至对Firebase更新,所以任何帮助都将不胜感激!

>解决方案

代码中的问题在于, snapshot 引用了 Favorites 节点 - 而不是查找 LocationName 那里,您应该在每个 Location 子节点内查找它。因此,你的循环应该看起来像这样:

$ p $ let databaseHandle = databaseRef.observe(.value,with:{snapshot in
为snapshot.children中的孩子{
let childSnapshot = snapshot.childSnapshotForPath(child.key)
如果让dbLocation = childSnapshot.value [LocationName] as?String {
print dbLocation)
}
}
})


I'm trying to loop through children in my Firebase Database to retrieve a nested key.

My database is structured like this:

"Users" : {
 "Username" : {
  "Favorites" : {
    "Location" : {
      "Latitude" : 123,
      "LocationName" : "San Francisco",
      "Longitude" : 123
    },
    "Location2" : {
      "Latitude" : 123,
      "LocationName" : "London",
      "Longitude" : 123
    }
  }
 }
}

I am trying to print out all of the "LocationName" keys, and am able to print one instance of this key, but not able to loop through and print all instances of this key.

I'm not sure where in my for loop I'm going wrong?

The code I'm working with is below.

    FIRApp.configure()

    let databaseRef = FIRDatabase.database().reference().child("Users").child("Username").child("Favorites")


    let databaseHandle = databaseRef.observe(.value, with: { (snapshot) in
        for item in snapshot.children {

            if let dbLocation = snapshot.childSnapshot(forPath: "LocationName") as? String {

                    print (dbLocation)
            }

            print(item)

        }

    })

I'm very new to Swift, and even newer to Firebase, so any help would be greatly appreciated!!

解决方案

The problem in your code is that snapshot refers to the Favorites node – instead of looking for LocationName there, you should look for it inside each of the Location child nodes. Therefore your loop should look something like this:

let databaseHandle = databaseRef.observe(.value, with: { snapshot in
    for child in snapshot.children {
        let childSnapshot = snapshot.childSnapshotForPath(child.key)
        if let dbLocation = childSnapshot.value["LocationName"] as? String {
            print(dbLocation)
        }
    }
})

这篇关于使用Swift在Firebase中遍历嵌套的快照子项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆