How to handle empty response using Alamofire and Combine?

Viewed 2217

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?

3 Answers

This error occurs when your backend returns no data but does not return an appropriate HTTP response code (204 or 205). If this is expected behavior for your backend, you can add your response code to the list of acceptable empty response codes when you set up the publisher: .publishDecodable(T.self, emptyResponseCodes: [200]. This also requires T to either conform to Alamofire's EmptyResponse protocol, or for you to expect Alamofire's Empty type as the response.

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>
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
                }
            }
Related