简体   繁体   中英

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?

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.

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

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM