ParseJson in Swift - login function

1

I have a method that does the verification of login and password using REST , but after reading I need to return a Bool value to validate if the login was done.

I do not know if I'm doing it the best way, anyway the problem is this: it finishes executing the function before answering me if the login was successful or wrong, and then it loads this information. >

See:

func logarNoSistema(email: String, senha: String) -> Bool
{
    var retorno: Bool = false

    let urlPath = "http://meuendereco/api/user/login?code=xxxxxx&email=\(email)&senha=\(senha)"
    let url = NSURL(string: urlPath)!
    let urlSession = NSURLSession.sharedSession()


    let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
        if (error != nil) {
            println(error.localizedDescription)
        }
        var err: NSError?

        var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary
        if (err != nil) {
            println("JSON Error \(err!.localizedDescription)")
        }

        let erro : Bool = jsonResult["erro"] as! Bool

        println(erro)
        println(jsonResult)

       //AQUI EU FAÇO A VERIFICAÇÃO SE O LOGIN DEU CERTO E SETO O RETORNO

        dispatch_async(dispatch_get_main_queue(), {

        })
    })
    jsonQuery.resume()


    return retorno
}
    
asked by anonymous 15.04.2015 / 04:11

1 answer

1

What happens is that you are doing an asynchronous data communication , so the return of the logarNoSistema method happens soon after the service call is triggered, without waiting for a return of the call.

What you need to do is to actually get your return after completing the service, so you'll need to delete the return of the method and use what Swift we call Closure , which is nothing more than a callback for your method.

Your method looks like this now (schematic just to illustrate):

func logarNoSistema(email: String, senha: String, loginResponse: (response: Bool) -> ()) {
    let url = NSURL(string: "http://pt.stackoverflow.com")

    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
        // Tratamento do JSON para então responder a condição abaixo
        if condicao {
            loginResponse(response: true)
        } else {
            loginResponse(response: false)
        }
    }

    task.resume()
}

Where condicao in this example above is what you will define if authentication succeeded.

Note that I have added one more argument to your method, this is the callback method, which will receive the response as soon as it exists. And then, call this method:

logarNoSistema("[email protected]", senha: "xpto") { (response) -> () in
    if response {
        // Sucesso :)
    } else {
        // Falha :(
    }
}
    
15.04.2015 / 14:09