我正在尝试从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
未保存。
答案 0 :(得分:1)
假设您的节点中有多个对象" currentGame"并且您正在寻找从所有这些中提取玩家地址坐标和当前游戏ID密钥,以下是如何执行此操作:
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"是您快照的孩子的孩子。 我猜你正在插入" currentGame"使用childByAutoId()。因此,您需要进一步展开它以访问它。
此外,如果您只需要访问一个孩子,您也可以使用:
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)
}
希望这有帮助!