0

So I am trying to fetch data from Firebase Firestore and put it into a local variable inside my function. Inside the function I created a variable for a name which is supposed to contain the value of the name of the user fetched from Firebase. The problem is that the variable name which is given the value of nameData (name from the database) is in reality never mutated. How should I do to get the name from the database and put it inside a variable?

public func fetchName(email: String) -> String {
        var name: String = "FIRST VALUE"
        
        database.collection(workerCollection).document(email).getDocument() {(querySnapshot, error) in
            if let error = error {
                print("Error getting documents: \(error)")
            } else {
                //get info about user
                if (querySnapshot != nil && querySnapshot!.exists){
                    let documentData = querySnapshot!.data()!
                    if let nameData = (documentData["Name"] as! String?){
                        name = nameData
                    }
                    print(name)
                }
            }
        }
        
    return name
}

2 Answers2

1

Add a completion handler in your function to get the name. Modify your function like this!

public func fetchName(email: String, Completion:@escaping((String)->()) {
    
    database.collection(workerCollection).document(email).getDocument() {(querySnapshot, error) in
        if let error = error {
            print("Error getting documents: \(error)")
        } else {
            //get info about user
            if (querySnapshot != nil && querySnapshot!.exists){
                let documentData = querySnapshot!.data()!
                if let nameData = (documentData["Name"] as! String?){
                    Completion(nameData)
                }
            }
        }
     }
  }

And then call that function in viewDidLoad or where ever you like.

fetchName(email: "a@b.com") { (name) in
        print(name)
    }
Coder
  • 508
  • 2
  • 13
0

Try this:

public func fetchName(email: String) -> String? {
        var name: String?
        
        name = database.collection(workerCollection).whereField("emailField", isEqualTo: email)

        dispatchQueue.main.async {
            return name
        }
}