我使用以下代码块作为我的项目中的通用网络组件,
AF.request(url, method: method ?? .post, parameters: requestParameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
completion(response)
}
我收到以下错误,
'responseJSON(queue:dataPreprocessor:emptyResponseCodes:emptyRequestMethods:options:completionHandler:)' 已弃用:responseJSON 已弃用,并将在 Alamofire 6 中删除。请改用 responseDecodable。
我尝试使用responseDecodable,但无法解码响应。我想知道解决这个问题的最准确的方法。
经过彻底研究后,我已经用更新的警告代码微调了解决方案。在这里,我删除了已弃用的responseJSON,并按照警告中的建议使用responseDecodable。在这里,我发布了我的整个函数并附有额外的注释,以便您可以更好地理解。
public static func get<T: Decodable>(url: String, parameters: [String: Any]? = nil, method: HTTPMethod = .post, completion: @escaping (Result<T, APIErrorResponse>) -> Void) {
let headers = Utilities.getRequestHeader() // Utility function gets headers
AF.request(url, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: headers)
.responseDecodable { (response: DataResponse<T , AFError>) in
switch response.result {
case .success(let value):
completion(.success(value))
case .failure(_):
if let statusCode = response.response?.statusCode {
switch statusCode {
case 400..<500:
// Client-side error
let genericError = APIErrorResponse(errorCode: statusCode, errorMessage: "Client-side error")
completion(.failure(genericError))
case 500..<600:
// Server-side errors
let serverError = APIErrorResponse(errorCode: statusCode, errorMessage: "Server-side error")
completion(.failure(serverError))
default:
let genericError = APIErrorResponse(errorCode: statusCode, errorMessage: "Unknown error")
completion(.failure(genericError))
}
} else {
let genericError = APIErrorResponse(errorCode: -1, errorMessage: "Unknown error")
completion(.failure(genericError))
}
}
}
}