我正在尝试从 Firebase 检索信息。我可以获取 JSON 格式的快照,但无法访问它并将值保存在我的应用程序中。
代码是这样的:
self.ref.child("users").child(userFound.userRef!).child("currentGame").observeSingleEvent(of: .value, with: { (snapshot) in
print(snapshot)
if let snapDict = snapshot.value as? [String:AnyObject] {
for each in snapDict {
self.theApp.currentGameIDKey = String(each.key)
self.currentGame.playerAddressCoordinates?.latitude = each.value["playerLatitude"] as! Double
print(self.theApp.playerAddressCoordinates?.latitude)
print(self.currentGame.currentGameIDKey)
}
}
})
这是它在控制台中的打印方式:
Snap (currentGame) {
"-KUZBVvbtVhJk9EeQAiL" = {
date = "2016-10-20 18:24:08 -0400";
playerAdress = "47 Calle Tacuba Mexico City DF 06010";
playerLatitude = "19.4354257";
playerLongitude = "-99.1365724";
};
}
currentGameIDKey
已保存,但 self.currentGame.playerAddressCoordinates
未保存。
最佳答案
假设您的节点“currentGame”中有多个对象,并且您希望从所有对象中提取玩家地址坐标和当前游戏 ID key ,下面是您可以如何做到这一点:
self.ref.child("users").child(userFound.userRef!).child("currentGame").observeSingleEvent(of: .value, with: { (snapshot) in
if(snapshot.exists()) {
let enumerator = snapshot.children
while let listObject = enumerator.nextObject() as? FIRDataSnapshot {
self.theApp.currentGameIDKey = listObject.key
let object = listObject.value as! [String: AnyObject]
self.currentGame.playerAddressCoordinates?.latitude = object["playerLatitude"] as! Double
print(self.theApp.playerAddressCoordinates?.latitude)
print(self.currentGame.currentGameIDKey)
}
}
根据您的数据库设计,您没有以正确的方式访问“playerLatitude”。 “playerLatitude”是您快照的 child 的 child 。 我猜您正在使用 childByAutoId() 插入“currentGame”。因此,您需要将其进一步展开一层才能访问它。
此外,如果您只需要访问一个 child ,您还可以使用:
self.ref.child("users").child(userFound.userRef!).child("currentGame").observeSingleEvent(of: .value, with: { (snapshot) in
if(snapshot.exists()) {
let currentGameSnapshot = snapshot.children.allObjects[0] as! FIRDataSnapshot
self.theApp.currentGameIDKey = currentGameSnapshot.key
self.currentGame.playerAddressCoordinates?.latitude = currentGameSnapshot.childSnapshot(forPath: "playerLatitude").value as! Double
print(self.theApp.playerAddressCoordinates?.latitude)
print(self.currentGame.currentGameIDKey)
}
希望这对您有所帮助!
关于json - 在 JSON 中从 Firebase 检索数据 - Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40165604/