Alamofire error is always nil, while request fails - swift

In case of 400(bad request) or 403(unauthorized) I can grab info about fail only from response, while error,passed in param is always nil - do it needs any extra setup?
Alamofire.request(Router.SignIn(emailField.text, passwordField.text)).response { (request, response, data, error) in
println(error)
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
UPD: as mattt advised added valide like this:
Alamofire.request(UdacityRouter.SignIn(emailField.text, passwordField.text)).validate().response
in
println(error)
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
As result I received "Optional("The operation couldn’t be completed. (com.alamofire.error error -1.)")" What is far away from meaningfull explanation of failure.. I wonder why I can't simply get error with a simple failure explanation as AFNetworking does..

Need to add .validate() because of by default, Alamofire treats any completed request to be successful, regardless of the content of the response.
From Alamofire documentation:
Validation
By default, Alamofire treats any completed request to be successful,
regardless of the content of the response. Calling validate before a
response handler causes an error to be generated if the response had
an unacceptable status code or MIME type.
Manual Validation
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.response { _, _, _, error in
println(error)
}
Automatic Validation
Automatically validates status code within 200...299 range, and that
the Content-Type header of the response matches the Accept header of
the request, if one is provided.
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
.validate()
.response { _, _, _, error in
println(error)
}

Related

How can I get the Responses Body in URLSession Swift?

) I'm trying to get the Error messages from the response's body to post request.
Here is the example of my code:
let task = URLSession.shared.dataTask(with: request) { _, response, error in
if let error = error {
print("Error took place \(error)")
} else {
print(response.?????)
}
What should I do to see the responses body?
You are ignoring the first parameter in the closure (_, response, error), and actually there is your data. Check the Apple sample to understand more https://developer.apple.com/documentation/foundation/url_loading_system/fetching_website_data_into_memory

Getting the returned error message from Alamofire

I am struggling to get the json error message returned using Alamofire and their .success / .failure method.
Before using this I could use response.result.value and get the returned error message but now I am validating the status code .validate(statusCode: 200..<300).
Have tried several things to receive the error but it always produces nil or just the status code.
Alamofire.request(url, method: .post, parameters: body, encoding: JSONEncoding.default)
.validate(statusCode: 200..<300)
.responseJSON { response in
switch response.result {
case .success:
//Other stuff
case .failure(let error):
print(response.result.value) //Produces nil when there is an error
print(error.localizedDescription)
print(response.result.error.customMirror)
print(response.result.error.debugDescription)
print(response.result.error.unsafelyUnwrapped)
print(response.result.error?.localizedDescription)
}
}
How can I get the error json? It is getting returned as such.
{
"status": "error",
"message": "Incorrect Password"
}
take that .validate() out. You will see more detailed description.

Order parameters using Alamofire

We are needing to control the parameter order in an Alamofire request. The parameters are supplied to Alamofire as a dictionary, and as such are not ordered.
Have also tried using an adapter, but by that time the body is encoded data, not thinking I can change that.
We need to order because of oauth, our server is using the params as part of the key and expecting a specific order.
Just in case, here is our code:
let parameters: Parameters = ["id": "userID","service": "token"]
Alamofire.request("https://ourhost.com", method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers)
.responseString { response in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
}
.responseJSON { response in
print(response.result)
switch response.result {
case .success:
print(response.result.value)
break;
default:
print(response.result.error!)
break
}
}
Would welcome a way to order these items.

Cannot call value of non-function type 'HTTPURLResponse?' Alamofire 4, Swift 3

I want to use Alamofire to send an email with Mailgun. I'm using the below code to send the request, but I'm getting error Cannot call value of non-function type 'HTTPURLResponse?' on line starting with .response.
How can I fix this? I'm trying to replicate the code found here but update it for Swift 3. I'm trying to send an email using Mailgun and Alamofire.
https://gist.github.com/makzan/11e8605f85352abf8dc1/
Thanks!
Alamofire.request(url, method: .post, parameters: parameters)
.authenticate(user: "api", password: key)
.response{ (request, response, data, error) in
println(request)
println(response)
println(error)
}
}
It's worth taking a look at the Alamofire migration pages for these sorts of issues.
You'll see there that responses are now handled like so:
// Alamofire 3
Alamofire.request(.GET, urlString).response { request, response, data, error in
print(request)
print(response)
print(data)
print(error)
}
// Alamofire 4
Alamofire.request(urlString).response { response in // method defaults to `.get`
debugPrint(response)
}

Alamofire POST Returning Data

I am using Alamofire to make a post request to server. The post request is working fine.
Issue: When the post request is made, it returns some data which I need. How can I store/ retrieve that data
The POST Request:
Alamofire.request(.POST, postURL, parameters: params)
to get the response closure add
.response { request, response, data, error in }
to the end of your code
ie
Alamofire.request(.POST, "http://httpbin.org/get", parameters: ["foo": "bar"])
.response { request, response, data, error in
print(request)
print(response)
print(data)
print(error)
}
If you are using the latest version of AlamoFire.
If you are using the latest version of AlamoFire.
Try this working fine for me.(Change request arguments based on your need)
let url1 = "http://yoururl.com"
let head = [ "Accept": "application/json;charset=UTF-8",
"Content-Type": "application/json;charset=UTF-8"] // Adding headers
let p = ["Email":"anything","Password": "123"] // Adding parameters if any
Alamofire.request(.POST,url1, parameters: p, encoding : .JSON, headers : head)
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
}