Returning name from Firestore?

寵の児 提交于 2021-02-17 07:17:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!