It is my first time for me to use Alamofire
, and it got me really frustrated.
I'm using the following code to call a signup API on the backend API
Alamofire.request(.POST, "\(self.authBaseURL)/signup", parameters: params, headers: headers, encoding: .JSON)
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseJSON { response in
switch response.result {
case .Success(let JSON):
print("Success with JSON: \(JSON)")
success(updatedUser)
case .Failure(let error):
print("Request failed with error: \(error)")
failure(error)
}
}
The problem is that the error object I'm getting in the .Failure
function doesn't contain the server side message.
I have tried to access the rest of the objects (request, response, data, result) I could not find my error message anywhere
I'm always getting the following error, no matter what the server message has to say. Request failed with error:
FAILURE: Error Domain=com.alamofire.error Code=-6003 "Response status code was unacceptable: 400" UserInfo={NSLocalizedFailureReason=Response status code was unacceptable: 400}
Is there is anything wrong I'm doing?
Swift 2.2, AlamoFire 3.3.0, Xcode 7.3
I managed to get it to work exactly the way I want is by dropping the status validation and check for the statusCode manually
Alamofire.request(.POST, "\(self.authBaseURL)/signup", parameters: params, headers: headers, encoding: .JSON)
.validate(contentType: ["application/json"])
.responseJSON { response in
if response.response?.statusCode == 200 {
print("Success with JSON: \(response.result.value)")
success(updatedUser)
}
else {
let error = response.result.value as! NSDictionary
let errorMessage = error.objectForKey("message") as! String
print(errorMessage)
failure(errorMessage)
}
}
This is how to get the error domain, code and user info with Alamofire 4 and Swift 3. User info contains the error strings.
Alamofire.request(.POST, "\(self.authBaseURL)/signup", parameters: params, headers: headers, encoding: .JSON)
.validate(statusCode: 200..<300)
.validate(contentType: ["application/json"])
.responseJSON { response in
switch response.result {
case .Success(let JSON):
print("Success with JSON: \(JSON)")
success(updatedUser)
case .Failure(let error):
let errorCode = error._code
let errorDomain = error._domain
let userInfo = error._userInfo
print("Request failed with error: \(error), code: \(errorCode), domain: \(errorDomain)")
failure(error)
}
}
updated for swift 3 :
Used below lines of code:-
Alamofire.request(escapedString!, method: .get, encoding: JSONEncoding.default)
.validate(contentType: ["application/json"])
.responseJSON { response in
if response.response?.statusCode == 200 {
print("Success with JSON: \(String(describing: response.result.value))")
}
else {
let error = (response.result.value as? [[String : AnyObject]])
print(error as Any)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With