问题
I'm trying to return a name after getting it on Firestore, but for some reason it's not working.
Here's my code:
func getName() -> String {
var name = ""
db.collection("users").whereField("email", isEqualTo: user.email!).getDocuments { (snapshot, error) in
if error != nil {
print(error!)
} else {
for document in (snapshot?.documents)! {
name = document.data()["name"] as! String
// if I add `print(name) here, it works.`
}
}
}
return name
}
But it returns an empty string :/ I want to return the actual name. How do I fix this?
回答1:
getDocuments
is an asynchronous function. This means the name
variable doesn't wait for the function to complete before continue executing. If you want to return the returned name from the document, you can take a look at the following code:
func getName(_ completion: (String) -> ()) {
db.collection("users").whereField("email", isEqualTo: user.email!).getDocuments { (snapshot, error) in
if error != nil {
print(error!)
} else {
for document in (snapshot?.documents)! {
name = document.data()["name"] as! String
completion(name)
}
}
}
}
getName { name in
print(name)
}
来源:https://stackoverflow.com/questions/55195703/returning-name-from-firestore