简体   繁体   English

如何使用 Alamofire 和 Combine 处理空响应?

[英]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其中 T 是

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?如何使用 Alamofire 和 Combine 处理带有空响应的发布请求?

This error occurs when your backend returns no data but does not return an appropriate HTTP response code (204 or 205).当您的后端未返回数据但未返回适当的 HTTP 响应代码(204 或 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.如果这是您的后端的预期行为,您可以在设置发布者时将响应代码添加到可接受的空响应代码列表中: .publishDecodable(T.self, emptyResponseCodes: [200] 。这也需要T符合到 Alamofire 的EmptyResponse协议,或者让您期望 Alamofire 的Empty类型作为响应。

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:像这样制作空 object :

struct EmptyEntity: Codable, EmptyResponse {
    
    static func emptyValue() -> EmptyEntity {
        return EmptyEntity.init()
    }
}

And return publisher like so:并像这样返回发布者:

-> AnyPublisher<EmptyEntity, AFError>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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