简体   繁体   English

使用Swift在Firebase中遍历嵌套的快照子级

[英]Iterate through nested snapshot children in Firebase using Swift

I'm trying to loop through children in my Firebase Database to retrieve a nested key. 我正在尝试遍历Firebase数据库中的子级以检索嵌套键。

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. 我正在尝试打印所有“ LocationName”键,并且能够打印该键的一个实例,但是无法循环遍历和打印此键的所有实例。

I'm not sure where in my for loop I'm going wrong? 我不确定在我的for循环中哪里出错了?

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!! 我是Swift的新手,甚至是Firebase的新手,因此,我们将不胜感激!

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. 代码中的问题是snapshot指向“ 收藏夹”节点-而不是在其中查找LocationName ,而应在每个Location子节点内查找snapshot 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)
        }
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM