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?

1
  • Look up “completion handler” and “callback function” Commented Sep 5, 2021 at 21:39

1 Answer 1

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)
                }
            }
        }
}
Sign up to request clarification or add additional context in comments.

1 Comment

It doesn't work, I've already tried completion handlers. var retVal = falseisUnique { (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)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.