공부/iOS
[iOS] status code가 200일 때 빈 응답이 들어오는 경우
안토니1
2024. 2. 17. 15:04
배경
Alamofire로 빈 타입으로 파싱을 시도하던 중에 오류가 발생했다.
응답은 status code는 200으로 들어오고 body가 비어있었는데, responseDecodable에서 "Empty"로 파싱을 시도했지만 inputDataNilOrZeroLength 오류가 발생했다.
해결법
해결법은 간단하게도 emptyResponseCodes 파라미터만 추가하면 됩니다.
emptyResponseCodes에 성공시킬 응답코드를 담은 배열을 추가해주면 오류가 해결됩니다.
func requestVerificationCode(email: String, completion: @escaping (Result<String, AuthError>) -> Void) {
let urlString = "http://localhost:8080/member/sendAuthenticationCode"
let parameters: [String: Any] = ["email": email]
let encoding: JSONEncoding = JSONEncoding.default
let headers: HTTPHeaders = ["Content-Type": "application/json"]
session
.request(urlString, method: .post, parameters: parameters, encoding: encoding, headers: headers)
.validate()
.responseDecodable(of: Empty.self, emptyResponseCodes: [200]) { response in
switch response.result {
case .success:
completion(.success("Verification code has been sent to your email"))
case .failure(let error):
completion(.failure(.networkError(error)))
}
}
}
레퍼런스
https://github.com/Alamofire/Alamofire/issues/2466#issuecomment-651822482
Error thrown for empty response content · Issue #2466 · Alamofire/Alamofire
Motivation Ability to make request to server that returns no content in some of the cases. Happy to contribute change if we agree that is an issue. What did you do? I have written Alamofire handler...
github.com