0

I have a fetch call is supposed to return a string, and this is how it looks:

func fetchCallTwo() -> String {
    let db = Firestore.firestore()
    let docRef = db.collection("path").document("subDoc")

    var returnableString: String = "DEFAULT VALUE"

    docRef.getDocument { (theDocument, error) in
        if let document = theDocument, document.exists {
            let field = document.get("field")

            if let field = field {
                print(field)

                returnableString = "\(field)"
            }
        }
    }

    print(returnableString)
    return returnableString
   }

However, this always returns "DEFAULT VALUE" instead of the value I want it to return, ie, the value fetched from my firebase server.

How do I rectify this?

2 Answers2

0

What you want to do is create a callback as a parameter inside the function.

func runFetch() {
    fetchCallTwo { (value) in
        // Do something
    }
}

func fetchCallTwo(callback: @escaping ((String) -> ())) {
 let db = Firestore.firestore()
 let docRef = db.collection("path").document("subDoc")

 var returnableString: String = "DEFAULT VALUE"

 docRef.getDocument { (theDocument, error) in
     if let document = theDocument, document.exists {
         let field = document.get("field")

         if let field = field {
             print(field)
            returnableString = field
         }
         callback(field)
     }
 }
}
Vollan
  • 1,887
  • 11
  • 26
0

In the above code, you're trying to do an async call, it won't work as expected, i.e. the fetchCallTwo() method would return even before the getDocument(_:) method receives the response.

You need to use closure to get that working.

func fetchCallTwo(handler: @escaping ((String)->())) {
    //rest of the code..
    var returnableString: String = "DEFAULT VALUE"
    docRef.getDocument { (theDocument, error) in
        if let document = theDocument, document.exists {
            let field = document.get("field")
            if let field = field {
                handler("\(field)")
            } else {
                handler(returnableString)
            }
        }
    }
}

Call the above method like,

fetchCallTwo { (str) in
    print(str)
}
Vollan
  • 1,887
  • 11
  • 26
PGDev
  • 23,751
  • 6
  • 34
  • 88