我的 database.swift 文件中有以下方法:
func GetTestData(arg: Bool, completion: ([Tweet]) -> ()) {
let db = Firestore.firestore()
var tweets = [Tweet]()
db.collection("tweets").getDocuments() {
querySnapshot, error in
if let error = error {
print("unable to retrieve documents \(error.localizedDescription)")
} else{
print("Found documebts")
tweets = querySnapshot!.documents.flatMap({Tweet(dictionary: $0.data())})
}
}
completion(tweets)
}
此方法连接到 Firestore
从给定集合中检索数据,将其转换为数组然后传回,我使用以下代码调用此函数(位于我的 TableView Controller 中):
func BlahTest() {
let database = Database()
print("going to get documents")
database.GetTestData(arg: true) { (tweets) in
self.tweets = tweets
self.tableView.reloadData()
}
print("after calling function")
}
我遇到的问题是当我运行它时我的代码不同步,我的意思是 print("after calling function")
在 print("Found documebts ")
这告诉我它没有等待对 Firestore
的异步调用完成,现在我是 iOS
开发的新手所以有人愿意提供帮助我明白我是如何处理这个的吗?
提前致谢。
最佳答案
您在 GetTestData()
方法中使用了闭包 block 。执行此方法后应该做的任何事情都必须在完成内完成:
{
(tweets) in
self.tweets = tweets
self.tableView.reloadData()
// Do rest of stuff here.
}
以下是一些关于像其他语言一样在 swift 中实现 async/await 的资源:
1. Async semantics proposal for Swift
2. AwaitKit : The ES8 Async/Await control flow for Swift
3. Concurrency in Swift: One approach
4. Managing async code in Swift
希望这有帮助:)
关于ios - 处理对 Firestore 的异步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47509109/