Parsejson on Swift - login function

Asked

Viewed 267 times

1

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

I don’t 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 went right or wrong, and only then it loads this information.

Look at:

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
}

1 answer

1


What happens is you’re making a asynchronous data communication, then the return of the method logarNoSistema happens soon after the call to the service is triggered, without expecting a return of this.

What you need to do is that your return comes in fact after completing the service, for that you will need to eliminate the return of the method and using what Swift we call it Closure, that is nothing more than a callback for your method.

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

func logarNoSistema(email: String, senha: String, loginResponse: (response: Bool) -> ()) {
    let url = NSURL(string: "http://answall.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 whether or not there was success in authentication.

Note that I added another argument to your method, this is the method of callback, you will receive the answer as soon as there is. And then, call this method:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.