簡體   English   中英

Swift:在下一次加載之前等待Firestore加載

[英]Swift: Wait for firestore load before next load

我有一個視圖控制器,列出了Firestore數據庫中的數據。 在firestore集合中,我有一堆文檔,其信息如列表所示,還有一個名為order文檔order其中包含一個字段,該字段是按我希望它們顯示的順序排列的字符串。 我的代碼抓住了這一點:

self.db.collection("officers").document(school).collection(grade).document("order").getDocument {(document, error) in
   if let document = document, document.exists {
     self.officerNames = (document.data()!["order"] as! Array<String>)

然后應該使用數組order的字符串( officerNames )來查詢同一集合中的文檔(所有文檔具有不同的role因此它僅在快照中獲得一個文檔)並以與顯示順序相同的順序顯示它們。一組按orderofficerNames )。

for item in 1...self.officerNames.count {
    self.db.collection("officers").document(school).collection(grade).whereField("role", isEqualTo: self.officerNames[item-1]).getDocuments() { (querySnapshot, err) in
       if let err = err {
          print("Error getting documents: \(err)")
       } else {
          for document in querySnapshot!.documents {
              let officerMessage = document.data()["agenda"] as! String
              let officerInfo = document.data()["short"] as! String
              (a bunch of code here using that ^ ^ and due to the color I need item to be an integer)
          }
       }
    }
}

我知道,如果我嘗試在self.collection("officers").....之前打印item ,則數字以1計數,但是如果我for document in querySnapshot.....for document in querySnapshot.....執行此操作,則它們全部用光了順序意味着某些文檔的加載速度比其他文檔更快。 我已經讀過Swift中的Async函數(盡管我確實在JavaScript中使用過這些函數),但實際上對如何使用它們感到困惑,希望有一種更簡單的方法可以做到這一點。 在再次遍歷循環之前,我可以等待任何方法來確保已加載並分析了先前的文檔嗎?

這是數據庫的屏幕截圖: 在此處輸入圖片說明

在此處輸入圖片說明

老實說,您可能想檢查一下數據結構,看看是否可以創建一個不需要多個查詢的數據結構。 我不太清楚您的數據結構是什么,但是如果您更新問題以使其包含在內,我可以為如何重構提供一些建議,這樣您就不必執行2個不同的get請求。

話雖這么說,但是由於Swift沒有像JS這樣的承諾,因此很難保證數據秩序井然。 正如我在此博客中所寫,在大多數情況下,閉包都可以正常工作。 但是它們仍然不會在異步調用數組中保留順序。 假設您使用某個數組存儲警官的數據,則可以通過為每個數組指定一個默認值來預先聲明數組的大小。 看起來像這樣:

var officerArray = [Officer](repeating:Officer(), count: self.officerNames.count)

當然,這取決於您使用哪種對象填充它。 在這種情況下,我使用了一些通用的Officer對象。

然后,不要將新創建的Officer對象(或您要調用的對象)附加到數組的末尾,而是將其值添加到數組中的特定位置。

for item in 1...self.officerNames.count {
    self.db.collection("officers").document(school).collection(grade).whereField("role", isEqualTo: self.officerNames[item-1]).getDocuments() { (querySnapshot, err) in
       if let err = err {
          print("Error getting documents: \(err)")
       } else {
          for document in querySnapshot!.documents {
              let officerMessage = document.data()["agenda"] as! String
              let officerInfo = document.data()["short"] as! String
              // etc
              officerArray[self.officerNames.count-1] = Officer(officerMessage: officerMessage, officerInfo: officerInfo) // or however you're instantiating your objects
          }
       }
    }
}

這樣可以保留訂單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM