【发布时间】:2020-10-23 16:23:30
【问题描述】:
我知道 Firebase getDocument 调用是异步的,所以我试图弄清楚如何基本上等到调用完成执行,然后继续做其他事情。
我尝试过使用 DispatchGroup() 并进入/离开组,但我似乎无法让它正常工作。我有类似以下内容:
let myGroup = DispatchGroup()
let usersRef = self.db.collection("Users").document("Users").collection("Users")
if self.testCondition == false {
self.errorMessage = "error"
} else{
usersRef.getDocuments {(snap, err) in
myGroup.enter()
//basically getting every username
for document in snap!.documents{
let user = document["username"] as! String
let userRef = usersRef.document(user)
userRef.getDocument { (snapshot, err) in
if err != nil {
print(err)
} else {
let sample = snapshot!["sample"] as! String
if sample == 'bad' {
self.errorMessage = "error"
}
}
}
}
myGroup.leave()
}
print("what4")
//I would like it so that I can execute everything in a code block like this
//after the async call finishes
myGroup.notify(queue: .main) {
print("Finished all requests.")
//THEN DO MORE STUFF
}
}
如何修改此处的 myGroup.enter() 和 myGroup.leave() 放置,以便在 Firebase 调用完成后,我可以继续执行代码?
谢谢!
【问题讨论】:
-
这是滥用
DispatchGroup的一个很好的例子。 不是此 API 的目的是强制单个异步任务变为同步。而等待异步任务的完成通常是错误的方法。推荐的方法是将//THEN DO MORE STUFF移动到getDocuments闭包内的循环末尾或添加完成处理程序。
标签: swift firebase google-cloud-firestore swiftui dispatch