Cod*_*het 1 ios firebase swift google-cloud-firestore
我的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)
}
Run Code Online (Sandbox Code Playgroud)
此方法连接以Firestore从给定的集合中检索数据,将其转换为数组,然后将其传递回,我使用以下命令(位于表视图控制器中)调用此函数:
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")
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是运行此代码时,我的代码不同步,这意味着print("after calling function")在调用它之前print("Found documebts"),它告诉我它不是在等待异步调用Firestore完成,现在我是新手,iOS所以有人愿意帮助我了解如何处理这个问题?
提前致谢。
您正在GetTestData()方法中使用闭包。执行此方法后应做的所有事情都必须在完成过程中完成:
{
(tweets) in
self.tweets = tweets
self.tableView.reloadData()
// Do rest of stuff here.
}
Run Code Online (Sandbox Code Playgroud)
以下是一些与其他语言一样快速实现异步/等待的资源:
希望这可以帮助 :)
| 归档时间: |
|
| 查看次数: |
498 次 |
| 最近记录: |