![](/img/trans.png)
[英][Firestore][I-FST000001] Could not reach Firestore backend
[英]Swift DispatchGroup causes error: [Firebase/Firestore][I-FST000001] Could not reach Cloud Firestore backend
我正在使用Firebase和Firestore通过以下方式读取数据:
var itemData: [String:Any]?
let docRef = db.collection("store").document(documentID)
let group = DispatchGroup()
group.enter()
DispatchQueue.global().async {
docRef.getDocument { (document, error) in
if let document = document, document.exists {
print("Document data: \(document.data() ?? ["key":"__data__"])")
itemData = document.data()
} else {
print("Document does not exist")
}
group.leave()
}
}
group.wait()
print("ITEM_DATA: \(itemData)")
return itemData
当我删除任何DispatchGroup,group.enter()等的所有引用时,代码可以正常运行,尽管不是我想要的顺序(即,它运行print("ITEM_DATA: \\(itemData)")
行,其中itemData为nil,直到以后才打印出print("Document data: \\(document.data() ?? ["key":"__data__"])")
)的结果。 因此,我知道对Firebase的实际请求没有任何问题。
但是,当我尝试在写入之前,使用上面的代码中的DispatchGroup来解决打印/返回itemData
的问题时,当我运行该函数时,程序会给我错误代码:
[Firebase/Firestore][I-FST000001] Could not reach Cloud Firestore backend. Backend didn't respond within 10.000000 seconds.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.
收到此消息后,该程序再也不会连接到Firestore。 我已经在有和没有wifi的模拟器和实际设备上进行了尝试,但是没有用。 我知道这不是我的Internet连接问题,因为当我用DispatchGroup删除所有内容时它可以工作,但是我仍然无法弄清楚问题是什么或如何解决此问题。
尝试进入和离开调度组在同一Queue
let group = DispatchGroup()
DispatchQueue.global().async {
group.enter()
docRef.getDocument { (document, error) in
if let document = document, document.exists {
print("Document data: \(document.data() ?? ["key":"__data__"])")
itemData = document.data()
} else {
print("Document does not exist")
}
group.leave()
}
}
group.wait()
print("ITEM_DATA: \(itemData)")
如果您想知道我的方法有何变化?
看看在DispatchQueue
异步关闭内部移动的enter语句
是什么原因引起的?
进入一个在不同队列中的调度组,而在另一个队列中离开调度组,可能是导致此问题的原因
编辑1:
嘿,刚刚测试了代码并使其正常工作
let group = DispatchGroup()
DispatchQueue.global().async {
group.enter()
sleep(10)
debugPrint("Hello")
group.leave()
}
group.notify(queue: DispatchQueue.main) {
print("ITEM_DATA: )")
}
这是控制台的输出顺序
我知道我没有使用wait()
并且wait()
应该也可以工作,但是我的工作有点忙,所以现在无法使用wait进行测试
编辑2:
刚刚意识到OP打算使用Dispatch group
从异步函数返回值,因此更新了我的答案
无论您采用哪种逻辑,都不能从异步调用获得return语句。 派遣小组在这里无济于事,您所需要的只是closure
或block
func test(onCompletion completion: @escaping ([String:Any]) -> ()) {
DispatchQueue.global().async {
docRef.getDocument { (document, error) in
if let document = document, document.exists {
completion(document.data())
}
}
}
}
并称之为
self.test {[weak self] (data) in
debugPrint(data)
}
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.