Alamofire 3 how to pick up errors if they exist in the call to the service(Swift2)

Asked

Viewed 77 times

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 can I know if there have been errors in communication and put a team out if it is taking too long.

I have tried the following code to get the 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

1 answer

3


The mistake was just in the completionHandler of the method responseJSON. It should look something 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 define a timeout, you need to first set its settings, including the time of timeout desired, 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 in this way:

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

Browser other questions tagged

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