[英]getdocuments function not stopping
so I'm trying to get data from firestore using this functionL所以我正在尝试使用此功能从 firestore 获取数据L
static func getData() -> [Post]{
let db = Firestore.firestore()
var posts = [Post]()
db.collection("Posts").getDocuments { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error retreiving snapshots \(error!)")
return
}
for document in snapshot.documents{
posts.append(Post(t: document.data()["title"] as? String ?? "", a: document.data()["author"] as? String ?? "", pm: document.data()["priceMax"] as? Double ?? 0.0, c: document.data()["content"] as? String ?? ""))
print("New Post... ")
print(document.data())
print(posts.count)
print(posts[0].title)
}
return
}
print("test")
return posts
}
and from the print statements I can tell that it gets the data, but the function never ends.从打印语句中我可以看出它获取了数据,但 function 永远不会结束。 print("test") never runs, and thus the posts are never returned. print("test") 永远不会运行,因此永远不会返回帖子。 How can I change this so that it returns the data?我怎样才能改变它以便它返回数据?
Getting data from Firestore is an asynchronous call.从 Firestore 获取数据是一个异步调用。 Try this out:试试这个:
func getData(completion: @escaping([Post], Error?) -> Void) {
let db = Firestore.firestore()
var posts = [Post]()
db.collection("Posts").getDocuments { querySnapshot, error in
guard let snapshot = querySnapshot else {
print("Error retreiving snapshots \(error!)")
completion(posts, error)
}
for document in snapshot.documents{
posts.append(Post(t: document.data()["title"] as? String ?? "", a: document.data()["author"] as? String ?? "", pm: document.data()["priceMax"] as? Double ?? 0.0, c: document.data()["content"] as? String ?? ""))
print("New Post... ")
print(document.data())
print(posts.count)
print(posts[0].title)
}
completion(posts, error)
}
}
Then call the function like this:然后像这样调用 function:
getData { posts, error in
print("Posts: \(posts)")
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.