【问题标题】:How to handle empty response using Alamofire and Combine?如何使用 Alamofire 和 Combine 处理空响应?
【发布时间】:2021-05-31 14:27:15
【问题描述】:

我正在发出一个帖子请求,但响应为空

AF.request(URL(string: "some url")!, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: nil)
    .validate()
    .publishDecodable(type: T.self)
    .value()
    .eraseToAnyPublisher()

T 在哪里

struct EmptyResponse: Codable {}

我遇到此错误“无法序列化响应,输入数据为零或零长度。” 如何使用 Alamofire 和 Combine 处理带有空响应的发布请求?

【问题讨论】:

    标签: ios swift alamofire combine


    【解决方案1】:

    当您的后端未返回数据但未返回适当的 HTTP 响应代码(204 或 205)时,会发生此错误。如果这是您的后端的预期行为,您可以在设置发布者时将响应代码添加到可接受的空响应代码列表中:.publishDecodable(T.self, emptyResponseCodes: [200]。这也要求 T 符合 Alamofire 的 EmptyResponse 协议,或者让您期望 Alamofire 的 Empty 类型作为响应。

    【讨论】:

    • 谢谢,我猜是“emptyResponseCodes: [200]”,这样工作的。
    • 我很难将 Combine 响应定义为 Empty 类型 -> AnyPublisher don't work 'Empty is ambiguous for type lookup
    • 我的后端没有发送任何内容和 204 代码我得到 Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength
    【解决方案2】:

    在其他地方找到了答案,但在这里很有用。像这样制作空对象:

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

    然后像这样返回发布者:

    -> AnyPublisher<EmptyEntity, AFError>
    

    【讨论】:

      【解决方案3】:
      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
                      }
                  }
      

      【讨论】:

        猜你喜欢
        • 2019-02-10
        • 1970-01-01
        • 2021-03-15
        • 2014-11-15
        • 2018-09-20
        • 1970-01-01
        • 2015-03-27
        • 1970-01-01
        相关资源
        最近更新 更多