0

The above code checks to make sure an email address is valid, this part works correctly. I can also retrieve the values correctly from the completion handler.

DispatchQueue.global(qos: .utility).async {
    let json = Json() 
    //check is email address exists using completion handler

    json.isEmailAddressValid(input:email!) { (result: Bool) in
    print("Result", result)

    DispatchQueue.main.async {         
        if (!(result)) {
            print("Email not found")
            message?.append("\nEmail Address does not exisit")
        }
    }
}

self.alert(message:message!)

I want to use the result variable when an email address is not found, then append Email Address not found message onto the concatenated string. I have tried many times, but the error message never gets shown within the alert view when using DispatchQueue. Am I using an incorrect thread?

Jankapunkt
  • 8,128
  • 4
  • 30
  • 59
BigMac
  • 49
  • 6
  • Why isn't the call to `self.alert(message:message!)` inside the call to `DispatchQueue.main.async`? Right now you show the alert long before the email has been validated. – rmaddy Jan 25 '18 at 22:06
  • Yep, just move `alert` to right after you `append` the message, inside that `DispatchQueue.main.async` call. – Rob Jan 25 '18 at 22:13
  • Thanks Rob for your quick response. Yes I made that change you suggested and now it works. Thanks. – BigMac Jan 26 '18 at 20:21

2 Answers2

0

The problem is that you are calling an asynchronous method, but not waiting for the result before continuing to execute your code.

The call to self.alert(message:message!) is executed before the closure is executed from json.isEmailAddressValid(input:email!) { (result: Bool) in.

To fix this, just move the alert into the DispatchQueue.main.async code block like this:

                DispatchQueue.main.async {

                    if (!(result)) {
                        print("Email not found")
                        message?.append("\nEmail Address does not exisit")

                    }
                    self.alert(message:message!)
                }

As a separate issue, you may not need to wrap all of this in the DispatchQueue.global(qos: .utility).async { block.

picciano
  • 22,341
  • 9
  • 69
  • 82
0

The self.alert(message:message!) needs to be called within the DispatchQueue.main.async closure.

When you call a DispatchQueue with the async method, the code after the async call is run, then later the code within the async closure is called. (That's is a simplification of what happens....)

For example:

print("A")
DispatchQueue.main.async {
    print("C")
}
print("B")

This code would print:

A 
B
C

The same thing in happening in your example, you show the alert first, then the results of isEmailAddressValid are processed, and then within that code within the DispatchQueue.main.async is processed.

Google "Grand Central Dispatch" or "GCD" for more information working with DispatchQueues

A. Johns
  • 199
  • 4