'How to handle empty response using Alamofire and Combine?
I am making a post request, which has an empty response
AF.request(URL(string: "some url")!, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate()
.publishDecodable(type: T.self)
.value()
.eraseToAnyPublisher()
where T is
struct EmptyResponse: Codable {}
and I am having this error "Response could not be serialized, input data was nil or zero length." How do I handle a post request with an empty response using Alamofire and Combine?
Solution 1:[1]
Found answer somewhere else but it's useful here. Made empty object like that:
struct EmptyEntity: Codable, EmptyResponse {
static func emptyValue() -> EmptyEntity {
return EmptyEntity.init()
}
}
And return publisher like so:
-> AnyPublisher<EmptyEntity, AFError>
Solution 2:[2]
AF.request(UrlUtils.base_url, method: .post, parameters: params, encoding: URLEncoding.default, headers: nil).responseJSON { (response:AFDataResponse<Any>) in
switch(response.result) {
case .success(_):
// this case handles http response code 200, so it will be a successful response
break
case .failure(_):
break
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lukasz D |
| Solution 2 | Mohammed Abdul Basith |
