使用Swift在Firebase中遍历嵌套的快照子项
我试图循环访问Firebase数据库中的子项以检索嵌套的密钥。
我的数据库是这样构造的:
"Users" : { "Username" : { "Favorites" : { "Location" : { "Latitude" : 123, "LocationName" : "San Francisco", "Longitude" : 123 }, "Location2" : { "Latitude" : 123, "LocationName" : "London", "Longitude" : 123 } } } }
我试图打印出所有的“LocationName”键,并且能够打印这个键的一个实例,但是不能够循环和打印这个键的所有实例。
我不知道我在哪里循环我要错了?
我正在使用的代码如下。
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) } })
我对Swift非常陌生,甚至对Firebase更新,所以任何帮助将不胜感激!
你的代码中的问题是, snapshot
引用了collections夹节点 – 而不是在那里寻找LocationName ,你应该在每个Location子节点中查找它。 因此你的循环应该看起来像这样:
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) } } })