![](/img/trans.png)
[英]How to handle empty array response in iOS swift using alamofire
[英]How to handle empty response using Alamofire and Combine?
我正在發出一個帖子請求,但響應為空
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 處理帶有空響應的發布請求?
當您的后端未返回數據但未返回適當的 HTTP 響應代碼(204 或 205)時,會發生此錯誤。 如果這是您的后端的預期行為,您可以在設置發布者時將響應代碼添加到可接受的空響應代碼列表中: .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
}
}
在其他地方找到了答案,但在這里很有用。 像這樣制作空 object :
struct EmptyEntity: Codable, EmptyResponse {
static func emptyValue() -> EmptyEntity {
return EmptyEntity.init()
}
}
並像這樣返回發布者:
-> AnyPublisher<EmptyEntity, AFError>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.