2016-11-20 32 views
-1

請解釋在哪裏(方法或可能存在與競爭方法觀察)我需要從Firebase檢索數據。什麼是最佳實踐?不能找到堆棧工作答案:如何知道Firebase何時檢索到數據

var ref:FIRDatabaseReference! 

    ref = FIRDatabase.database().reference() 

    //filling ShopList by favorite 
    ref.child("goods").observeSingleEvent(of:.value, with: {(snapshot) in 
     if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] { 

      print("my app: 1. Start ObserveSingle") 

      for snap in snapshots { 

       let g = Good() 
       g.barcode = String(describing: snap.childSnapshot(forPath: "barcode").value!) 
       g.name = snap.childSnapshot(forPath: "name").value! as! String 
       g.price = snap.childSnapshot(forPath: "minprice").value! as! Double 
       g.favorite = snap.childSnapshot(forPath: "favorite").value! as! Bool 

       if g.favorite {//избранные товары 
        DataService.dataService.dbShopList.append(g) 
       } 
      } 

      print("my app: 2. Observe finished \(DataService.dataService.dbShopList.count)") 
     } 

    }) 

    print("my app: 3. observe finished \(DataService.dataService.dbShopList.count)") 

如何理解何時何地完成第2步

調試下面

my app: 3. observe finished 0 
    my app: 1. Start ObserveSingle 
    my app: 2. Observe finished 3 
+1

什麼是你想用問嗎?您的印刷品會在事情發生時顯示給您 – jonrsharpe

回答

0

火力地堡的數據是繼觀察封閉內纔有效。所以,當你調用

ref.child("goods").observeSingleEvent(of:.value, with: { 
    //this is the closure where the data is returned and valid 
}) 

這裏的俘獲....

print("my app: 3. 

將被調用之前

print("my app: 2. 

因爲代碼的執行速度比互聯網更快!

Firebase返回的數據有延遲,導致關閉在之後觸發關閉之外的打印語句。

使用Firebase數據INSIDE閉包,因爲這是唯一有效的時間。在數據準備就緒之前嘗試訪問數據將導致無數據,因爲在調用閉包之前變量將不會被填充。

根據返回的Firebase數據習慣設置事件序列需要時間。

下面是一些僞代碼:

myDataSource = [] 

Query Firebase for data { 
    populate the data source with Firebase data 
    reload the tableView 
} 

don't access the data source here as it won't be ready 

我們可以使用的代碼片段將它放入做法從你的問題

var ref:FIRDatabaseReference! 
ref = FIRDatabase.database().reference() 

ref.child("goods").observeSingleEvent(of:.value, with: {(snapshot) in 

    print("data from the snapshot is ready to be used") 

    for child in snapshot.children { 
     var g = Good() 
     let snap = child as! FIRDataSnapshot 
     let dict = snap.value! as! [String:String] 
     g.barcode = dict["barcode"]! 
     DataService.dataService.dbShopList.append(g) 
    } 

    print("All the firebase data was read in, show it in the tableView") 
    self.tableView.reloadData() 

}) 

print("This will execute before the closure completes so") 
print(" don't do anything with the Firebase data here") 
+0

感謝你的理論,你能舉一個練習的例子嗎? – LEONID

+0

@LeonifNif我不知道是否可以舉一個例子,因爲你的代碼很好 - 它是理解數據流的問題。 Firebase本質上是異步的,因此您無法使用快照數據,直到Firebase返回該數據 - 並且數據只在觀察封閉內有效。我添加了一些示例代碼(未在我的iPad上進行測試),可以引導您完成流程。 – Jay

+0

謝謝。有用!!!!! – LEONID

相關問題