so I'm trying to get data from firestore using this functionL
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. print("test") never runs, and thus the posts are never returned. How can I change this so that it returns the data?
CodePudding user response:
Getting data from Firestore is an asynchronous call. 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:
getData { posts, error in
print("Posts: \(posts)")
}