簡體   English   中英

Swift-與DispatchGroup()異步從Firebase Firestore下載數據時出現問題

[英]Swift - Problem While Downloading Data From Firebase Firestore Asynchronously with DispatchGroup()

在“事件”集合中獲取其EventStatus值等於0的每個文檔的ID並將其存儲在字符串數組(documentIds)中的同時,我嘗試使用DispatchGroup()異步運行代碼,因此當我返回“ documentIds”時,我會返回一個非空且完整的值。

但是,當我按如下所示運行代碼時,它凍結了,實際上它從未在getDocuments {}閉包中運行。

我試圖在DispatchQueue.global()。async {}中運行getDocuments {}閉包,但是它也沒有起作用。

func someFunction() -> [String] {

var documentIds : [String]!
var dispatchGroup = DispatchGroup()
dispatchGroup.enter()

Firestore.firestore().collection("events").whereField("EventStatus", isEqualTo: 0).getDocuments { (snap, error) in

        if let error = error {
            print(error.localizedDescription)
            return
        }

        guard let snap = snap else { return }

        documentIds = snap.documents.map({ (document) -> String in
            return document.documentID
        })

        dispatchGroup.leave()

    }

dispatchGroup.wait()
return documentIds

}

當凍結時,firebase在調試控制台中給出了此錯誤:

“無法訪問Cloud Firestore后端。后端在10秒鍾內沒有響應。這通常表明您的設備目前無法正常運行Internet。客戶端將以脫機模式運行,直到能夠成功連接到后端。”

除此之外,沒有錯誤或其他反饋。 我在DispatchGroup()或Firestore上做錯什么了嗎?

謝謝您的幫助!

這是dispatchGroup無效並導致許多錯誤的情況之一。

由於從Firestore檢索數據是異步調用,因此請對方法使用完成處理程序,而不要返回值並擺脫dispatchGroup

func someFunction(completion: @escaping ([String]) -> Void) {

    Firestore.firestore().collection("events").whereField("EventStatus", isEqualTo: 0).getDocuments { snap, error in

        if let error = error {
            print(error.localizedDescription)
            return
        }

        guard let snap = snap else { return }

        var documentIds = snap.documents { document in
            return document.documentID
        }

        completion(documentIds)
    }

}

然后使用完成處理程序調用您的方法,您可以在其中訪問接收到的String數組

someFunction { documentIds in // name completion parameter of type `[String]`
    ... // assign some global array as `documentIds` and then reload data, etc.
}

暫無
暫無

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

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