在获取“事件”集合中每个文档的 ID(其中它们的 EventStatus 值等于 0)并将它们存储在字符串数组 (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 秒内没有响应。 这通常表示您的设备目前没有正常的互联网连接。客户端将以离线模式运行,直到它能够成功连接到后端。”
除此之外,没有错误或其他一些反馈。我对 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.
}
关于ios - Swift - 使用 DispatchGroup() 从 Firebase Firestore 异步下载数据时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54097857/