我试图在最后一个故事板中显示分数。我的意思是在比赛结束后,但它没有显示得分的更新值。相反,它显示上一个游戏的价值。在Firebase控制台中,值会更新。我希望你能理解我的问题。
这是比较当前标签中的值和数据库中存储的值的代码,如果当前值大于DB中的值然后覆盖它,则不然,然后执行segue并显示新的大值存储在数据库中的值。
func getDatabaseScore(completion: @escaping (Int?)->()) {
let ref = FIRDatabase.database().reference().child("users").child("user").child(userid)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
if let userDict = snapshot.value as? [String:Any] {
//Do not cast print it directly may be score is Int not string
completion(userDict["score"] as! Int?)
print(userDict["score"] as! Int?)
}
completion(nil)
})
}
func Counting() {
counter -= 1
timer.text = "\(counter)"
if counter == 0 {
timerCounter.invalidate()
timerRunning = false
self.getDatabaseScore() { score in
// do something with "score"
guard let score = score else { return }
if score < self.scoreCounter{
print(self.scoreCounter)
ref.child("user").child((user?.uid)!).child("score").setValue(self.scoreCounter)
}
}
print(self.scoreCounter)
DispatchQueue.main.async{
self.performSegue(withIdentifier: "resultView", sender: self)
}
}
}
以下是我在标签上显示分数的最后一个segue的代码,问题是它没有显示刚刚结束的当前游戏的更新值:
override func viewDidLoad() {
super.viewDidLoad()
FIRDatabase.database().reference().child("users").child("user").child(username).observe(.value, with: { (snapshot) in
if let userDict2 = snapshot.value as? [String:Any] {
print(userDict2["score"])
self.resultLabel.text = "\(userDict2["score"] as! Int?)"
}
})
// Do any additional setup after loading the view.
}