I want a diffrerent responseDecodable on the httpStatusCode
server return
if statusCode == 200
resonseBody
{id: number}
if statusCode 400..<500
resonseBody
{
code: String
timestamp: String
message: String
}
so now my code is
AF.request(url, method: .post, headers: header).responseData { response in
switch response.result {
case .success(let data) :
guard let response = response.response else {return}
let json = try? JSONSerialization.jsonObject(with: data)
switch response.statusCode {
case 200:
if let json = json as? [String: Any] , let message = json["id"] as? Int{print(message)}
case (400..<500):
if let json = json as? [String: Any] , let message = json["message"] as? String{print(message)}
default:
return
}
case .failure(let err) :
print(err)
}
}
I try this code convert responseDecodable
struct a: Codable {var id: Int}
struct b: Codable{
var code: String
var timestamp: String
var message: String
}
AF.request(url, method: .post, headers: header).responseDecodable(of: a.self) { response in
guard let data = response.value else {return}
print(data)
}
.responseDecodable(of: b.self) { response in
guard let data = response.value else {return}
print(data)
}
but this way Regardless statusCode return both a and b
I want stautsCode == 200 return a or statusCode 400..<500 return b
What should I Do?
AFAIK, Alamofire does not have a “decode one object for success and another for failure” implementation. You'll have to do this yourself.
If you really want a one distinct object for 2xx responses and another for 4xx responses, there are a few approaches:
Use
validateto handle the 2xx responses, and manually decode 4xx responses in the error handler.If you want, you could write your own
ResponseSerializerto parse 2xx and 4xx responses differently:And then you can do:
I find the nesting of the parsed error object to be a little tedious, but it does abstract the 2xx vs 4xx logic out of the
response/responseDecodercompletion handler.In both of these, I'm considering all 2xx responses as success, not just 200. Some servers return 2xx codes other than just 200.