代码正在跳过firebase快照

时间:2017-05-24 17:08:46

标签: ios swift firebase firebase-realtime-database

我正在尝试运行以下代码,但由于某种原因,快照永远不会因为while循环而运行。当我添加while循环时,唯一打印的是"current count is <2",因为上面的currentCount的赋值由于某种原因被跳过。这是代码:

override func viewDidLoad() { 
    //below sets the default selection as pitcher
    pitcher = true
    batter = false
    //******Needs to show the default selection as well
    batterCheck.hidden = true
    batterButton.tintColor = UIColor.blueColor()
    pitcherButton.tintColor = UIColor.blueColor()

    //below defaults to hiding the results related data
    ResultsLabel.hidden = true
    playName.hidden = true
    pointDiff.hidden = true

    var playRef = ref.child("LiveGames").child("05-25-17").child("RedSox")
    playRef.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
        self.currentCount = Int(snapshot.childrenCount)
        print(snapshot.childrenCount)
        print(snapshot)
        print("***" + String(self.currentCount))
    })

    while(self.ended != true) {
        if(self.currentCount < 2) {
            print("current count is < 2")

        } else {
            playRef.child(String(self.currentCount-2)).observeSingleEventOfType(.Value, withBlock: { (snapshot2) in
                var hitterRef = snapshot2.childSnapshotForPath("/Hitter")
                var pitcherRef = snapshot2.childSnapshotForPath("/Pitcher")
                self.batterName.text = (String(hitterRef.childSnapshotForPath("/fName")) + " " + String(hitterRef.childSnapshotForPath("/lname")))
                self.pitcherName.text = (String(pitcherRef.childSnapshotForPath("/fName")) + " " + String(pitcherRef.childSnapshotForPath("/lname")))

            })
            self.currentCount += 1
        }
    }
    print("labels updated")

}

但是当我注释掉while循环时,currentCount被设置为正确的值。关于这个while循环正在做什么阻止firebase快照运行的任何想法?

2 个答案:

答案 0 :(得分:2)

observeSingleEventOfType:withBlock是异步调用的。这意味着它将在另一个线程中执行,而不是在ViewDidLoad方法的范围内执行。

如果你在完井区外面留下一个断点,而在完井区内有一个断点,它会变得更清晰。

如果您需要在&#39; observeSingleEventOfType&#39;之后更新标签,您需要做什么?已完成,您应该移动您更新&#39;代码在一个单独的方法中,并在observeSingleEventOfType方法的完成块中调用它。

示例:

override func viewDidLoad() {
 //Your code here...
 var playRef = ref.child("LiveGames").child("05-25-17").child("RedSox")
    playRef.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
        self.currentCount = Int(snapshot.childrenCount)
        self.updateLabels()
    })
   //Your code here...
}
func updateLabels() {
  //Your update code here...
}

答案 1 :(得分:0)

当我没有为观察的父母设定规则时,我也遇到了这个问题。