我正在试图从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密钥,那么您可以这样做:
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”是快照子对象的子对象。
我猜你正在使用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)
}
希望这有帮助!