Can't refresh UI after async call
<p>What I want to do: I have a login screen, the user fill the username and password, and then it press the login button. An async call to the server is done to check if user is registered and password is okay, and if yes (async function set a bool to yes) then do a segue to the next view controller. Simple as that, I've tried many ways but with always the same problem, the main thread runs the <code>shouldPerformSegueWithIdentifier</code> method, do the async call and check the global bool var (false by default) before the background thread has updated it, so the segue is not performed because the global variable is set to true AFTER. Only if I use sleep(1) the UI is refreshed but I don't want to use this. Is there a way to do this without sleep?? Every method I run has a completion handler.
I don't know how to sync the main with the background thread. I've read it's posible to update UI from async call so this should be posible. I've been looking questions for a while and tried lot of snippets, and still haven't found a solution for my problem. 
This is the code I have so far:</p>

<pre><code>    override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -&gt; Bool {

    let apiCall = webApi()

    dispatch_async(dispatch_get_main_queue()) {

        apiCall.callCheckIsUserLogged(nil, password : self.passwordField.text, email: self.mailField.text){ (ok) in
        }
    }
//sleep(1) if I uncomment this, my method works because it will return true
    return userIsLogged
}
</code></pre>

<p><code>apiCall.callCheckIsUserLogged()</code> : </p>

<pre><code>typealias successClosure = (success : Bool) -&gt; Void
    //Make a call to check if the user exist, server returns json with success or failure
func callCheckIsUserLogged(username: String?, password : String?, email: String?,completed : successClosure){

    userApiCallUrl = "http://apiurl.com/users/login"

    let call = asyncCallClass()
    call.doAsyncCallWithParams(userApiCallUrl, calltype: "POST", username: username, pass: password, mail: email){ (success) in
        completed(success: true)
    }

}
</code></pre>

<p><code>call.doAsyncCallWithParams()</code> code:</p>

<pre><code>internal typealias completion = (success : Bool) -&gt; Void
private var flagCompletion : Bool = false

        //Handle async class with this method
//var callType is aditioned everytime an arg is not passed nil.
//callType == 3 it is a call to check if user is logged
//callType == 2 is a call to register a new user
func doAsyncCallWithParams(url : String, calltype : String, username : String?, pass : String?, mail : String?, completed : completion){

    var callType : Int = 0


    //Set Async Url
    setUrl(url)

    //Set Post Params
    if let user : String = username{
        self.username = "username=\(user)"
        callType += 1
    }
    if let password : String = pass{
        self.password = "password=\(password)"
        callType += 1
    }
    if let mail : String = mail{
        self.email = "email=\(mail)"
        callType += 1
    }

    //register a new user
    if(callType == 3){
        paramString = "\(self.username)&amp;\(self.password)&amp;\(self.email)"

    }
    //check if user is logged, send email and password
    if(callType == 2){
        paramString = "\(self.email)&amp;\(self.password)"
    }

    //Do call
    callWithCompletionHandler { (success) in
        self.flagCompletion = true
        completed(success: self.flagCompletion)
    }
}
</code></pre>

<p><code>callWithCompletionHandler()</code> code: </p>

<pre><code>private typealias completionAsyncCall = (success : Bool) -&gt; Void
    private func callWithCompletionHandler(completed : completionAsyncCall){
        asyncJson.removeAllObjects()

        //Set async call params
        let request = NSMutableURLRequest(URL: NSURL(string: self.url!)!)
        request.HTTPMethod = "POST"
        let trimmedPostParam : String = self.paramString!.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

        request.HTTPBody = trimmedPostParam.dataUsingEncoding(NSUTF8StringEncoding)

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
            guard error == nil &amp;&amp; data != nil else {
                // check for fundamental networking error
                print("error=\(error)")
                return
            }
            if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
                // check for http errors
                print("statusCode should be 200, but is \(httpStatus.statusCode)")
                print("response = \(response)")
            }

            let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)


            let result : AnyObject = responseString!.parseJSONString!

                if let nsMutableResult = result as? NSMutableArray{
                    print("NSMutableArray")
                }
                if let nsDictResult = result as? NSMutableDictionary{
                    self.parseMutableDictionary(nsDictResult)
                }


            self.flag = true  // true if download succeed,false otherwise
            completed(success: flagAsyncCall!)
        }
        task.resume()
    }
</code></pre>