2016-10-20 44 views
0

Firebaseから情報を取得しようとしています。私はJSONでスナップショットを取得することができますが、私はそれにアクセスし、私のアプリに値を保存することに問題があります。JSONでFirebaseからデータを取得 - Swift

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

リターン出力が正しいjson形式でない –

+0

@cosmosこれを確認してください。http://stackoverflow.com/questions/40078420/how-to-extract-child-of-node-in-data-snapshot/40078667#40078667 –

答えて

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」はスナップショットの子の子です。 childByAutoId()を使って "currentGame"に挿入していると思います。したがって、アクセスするにはさらに1レベルを展開する必要があります。また

、あなただけの一人の子供にアクセスする必要があれば、あなたも使用することができます。

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) 

      } 

・ホープこのことができます!

関連する問題