2016-10-20 2 views
0

Я пытаюсь получить информацию из Firebase. Я могу получить моментальный снимок в JSON, но у меня возникают проблемы с его доступом и сохранением значений в моем приложении.Извлечение данных из Firebase в JSON - 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

return output не в правильном формате json –

+0

@cosmos проверить это http://stackoverflow.com/questions/40078420/how-to-extract-child-of-node-in-data-snapshot/40078667#40078667 –

ответ

1

Если предположить, что у вас есть несколько объектов в вашем узле «currentGame» и вы хотите, чтобы извлечь координаты игрок адрес и текущий игровой идентификатор ключа от всех из них, вот как вы можете это сделать:

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) 

      } 

Надеется, что это помогает!

Смежные вопросы