需要从firebase数据库获取值并将其存储在本地变量中

时间:2017-06-29 04:11:30

标签: ios swift firebase firebase-realtime-database

游戏需要保持用户玩过的游戏数量。 var“gamesPlayed:Int”记录了这一点。 当用户重新启动游戏并且删除了存储在gamesPlayed中的值时,问题出现了,我尝试在应用程序启动时从数据库中提取gamesPlayed的值,并将其分配给变量,但它似乎不起作用。 / p>

JSON

    `users
 K7g3KamKXfb8IlgqjEgAj9uQFGZ2
 game-1
 GAME-NUMBER: 1
 REACTION-TIME: .5
 SCORE: 10
 SWIPES: 10`

我的代码

var gamesPlayed :Int?
    var tempGamesPlayed :Int?
let userID = KeychainWrapper.standard.string(forKey: KEY_UID)
let getref = Database.database().reference().child("users").child(userID!).queryOrderedByValue().observeSingleEvent(of: .value, with: { (snapshot) in

                if snapshot.exists() {
                          print("we have that snapshot, the id is \(snapshot.value!)")
                         self.tempGamesPlayed = snapshot.value(forKey: "GAME-NUMBER")
                    print("tempgames is \(self.tempGamesPlayed)")
                    } else {
                      print("we don't have that")
                }
            })
            if tempGamesPlayed == nil
            {
                gamesPlayed = 0

            }
            else
            {
                gamesPlayed = tempGamesPlayed!

            }
            gamesPlayed! += 1

            let ref = Database.database().reference().child("users").child(userID!).child("game-\(gamesPlayed!)")

            if swipes > 0
            {
            ref.updateChildValues([
                "SCORE": c,
                "SWIPES": swipes,
                "REACTION-TIME": reactTime,
                "GAME-NUMBER": gamesPlayed!
                ])
            }
            else
            {
                ref.updateChildValues([
                    "SCORE": 0,
                    "SWIPES": 0,
                    "REACTION-TIME": 0,
                    "GAME-NUMBER": gamesPlayed!
                    ])
                }

任何帮助将不胜感激!

0 个答案:

没有答案