[英]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.