Returning name from Firestore?

前端 未结 1 711
北荒
北荒 2021-01-29 13:35

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 {

               


        
相关标签:
1条回答
  • 2021-01-29 14:02

    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)
    }
    
    0 讨论(0)
提交回复
热议问题