2017-05-24 84 views
0

我想運行下面的代碼,但由於某種原因,快照從不運行作爲while循環的結果。當我添加while循環時,唯一打印的是"current count is <2",因爲上面的currentCount的分配由於某種原因被跳過。下面是代碼:代碼跳過firebase快照

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

observeSingleEventOfType:withBlock被異步調用。這意味着它將在另一個線程中執行,而不是在ViewDidLoad方法的範圍內。

如果你在完成塊外面附加一個斷點,在完成塊裏面附加一個斷點,它將變得更加清晰。

如果您需要在'observeSingleEventOfType'完成後更新標籤,您需要執行的操作是,應該在單獨的方法中移動'更新'代碼並在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... 
}