[英]Handle non JSON Response with Generic Codable API client
我有一個API客戶端,該客戶端使用符合Codable協議的通用API響應,並使用JSONDecoder
解碼響應,如下所示,如何處理不返回JSON的響應(已創建狀態代碼201)?
dataRequest.validate().responseJSON { response in
if let error = response.error {
completion(.failure(error.localizedDescription))
} else if let data = response.data {
do {
let apiResponse = try JSONDecoder().decode(T.Response.self, from: data)
completion(.success(apiResponse))
} catch {
completion(.failure(error.localizedDescription))
}
} else {
completion(.failure("Something went wrong, please try again later."))
}
}
它返回此錯誤:響應無法序列化,輸入數據為nil或零長度
在這種情況下,您可以查看response
的statusCode
屬性(假設它是HTTPURLResponse
),然后確定是否有要解析的正文。 我將在錯誤檢查后立即將其放置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.