Alamofire 3 how to get errors if there is a service call (Swift2)

1

I have the following code to call the server

   Alamofire.request(mutableURLRequest)
        .responseJSON{ request, response, result in
           response in
            if let value: AnyObject = response.result.value {

                    let post = JSON(value)
                    print(post[0])
            }
            else
            {
                 print("**ERRO**")
            }
    }

My question is how do I know if there were any errors in the communication and put a timeout in case it is taking too long.

I have tried the following code to look for possible errors:

Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
.responseJSON { request, response, result in
    switch result {
    case .Success(let JSON):
        print("Success with JSON: \(JSON)")
    case .Failure(let data, let error):
        print(error)
    }
}

But I get the following error:

Contextual type for closure argument list expects 1 argument, but 3 were specified

    
asked by anonymous 17.02.2016 / 12:00

1 answer

3

The misunderstanding was only in% with% of method completionHandler . It should look like this:

Alamofire.request(.GET, url, parameters: ["foo": "bar"]).responseJSON { response in
    switch response.result {
    case .Success(let data):
        // Sucesso
    case .Failure(let error):
        // Error
    }
}

Now to set a timeout , you need to first define its settings, including the desired timeout time, which will change your request. Something like this:

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.timeoutIntervalForRequest = 20
configuration.timeoutIntervalForResource = 20

let alamoFireManager: Alamofire.Manager = Alamofire.Manager(configuration: configuration)

And then, your request will be made by this object this way:

alamoFireManager.request(.GET, url, parameters: ["foo": "bar"]).responseJSON { response in
    // Restante do código...
}
    
17.02.2016 / 12:11