0

I'm trying to set a variable to a boolean based on this code here:

Firestore.firestore().collection("users").whereField("username", isEqualTo: usernameTextField.text!).getDocuments
            { (querySnapshot, error) in
                if let error = error { print(error.localizedDescription) /*ALERT*/ }
                else
                {
                    if querySnapshot!.isEmpty
                    {
                        print("QuerySnapshot is empty, this is unique")
                        retVal = true
                    }
                    else
                    {
                        print("There's a bloody username in here, get a new one")
                        retVal = false
                    }
                }
            }
            return retVal

The issue is however, retVal is not changed. I understand what's going on here, it's an asynchronous block of code, however I don't understand how to fix it or work around it to fit my needs. How do I get the value of retVal, (or honestly just return true or false within this block of code) despite it being asynchronous. Is there anyway I can like wait for it to finish before further execution of code?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
EAO123
  • 55
  • 9

1 Answers1

1

Since your call is asynchronous, you should use a callback or completion handler in your function, this way the retVal will be returned when the Firestore query finishes.

Something like this:

func userIsUnique(completionHandler: (Bool) -> Void) {
 Firestore.firestore().collection("users").whereField("username", isEqualTo: usernameTextField.text!).getDocuments
        { (querySnapshot, error) in
            if let error = error { print(error.localizedDescription) /*ALERT*/ }
            else
            {
                if querySnapshot!.isEmpty
                {
                    print("QuerySnapshot is empty, this is unique")
                    completionHandler(true)
                }
                else
                {
                    print("There's a bloody username in here, get a new one")
                    completionHandler(false)
                }
            }
        }
}
  • It doesn't work, I've already tried completion handlers. var retVal = false```isUnique { (bool) in retVal = bool } print("THIS IS THE RET VALUE: " + String(retVal)) if retVal == false { return retVal }``` (Sorry for the annoying spaces i don't know how to fix it) – EAO123 Sep 06 '21 at 00:53