Soy nuevo en Swift y estoy tratando de actualizar un código Swift antiguo. Recibo la siguiente advertencia:
'responseJSON(queue:dataPreprocessor:emptyResponseCodes:emptyRequestMethods:options:completionHandler:)' está en desuso: responseJSON está en desuso y se eliminará en Alamofire 6. Use responseDecodable en su lugar.
... en el siguiente código:
extension Alamofire.DataRequest { func json(_ options: JSONSerialization.ReadingOptions = .allowFragments, successHandler: ((Any?) -> Void)? = nil, failureHandler: ((AFDataResponse<Any>) -> Void)? = nil) -> Self { return responseJSON() { response in if UtilityService.ensureSuccessful(response, failureHandler: { failureHandler?(response) }) { successHandler?(response.value) } NetworkActivityManager.sharedInstance.decrementActivityCount() } } }Si reemplazo responseJSON con responseDecodable, aparece este error:
No se pudo inferir el parámetro genérico 'T'
¿Qué debo hacer para actualizar este código?
Alamofire recomienda usar responseDecodable() porque las personas a menudo usaban responseJSON() , luego obtenían response.data y llamaban a un JSONDecoder() en él. Entonces esto estaba haciendo una llamada interna de JSONSerialization para "nada". Además, dado que Codable es "nuevo" y todavía había preguntas antiguas disponibles, es posible que a las personas les falte la función Codable. Consulte este tema en Alamofire Repo.
Entonces, si usa Codable , lo animo cuando sea posible, use responseDecodable() en su lugar.
Pero aún puede hacerlo manualmente, recuperando Data sin conversión:
Para eso, usa:
@discardableResult func responseData(queue: DispatchQueue = .main, dataPreprocessor: DataPreprocessor = DataResponseSerializer.defaultDataPreprocessor, emptyResponseCodes: Set<Int> = DataResponseSerializer.defaultEmptyResponseCodes, emptyRequestMethods: Set<HTTPMethod> = DataResponseSerializer.defaultEmptyRequestMethods, completionHandler: @escaping (AFDataResponse<Data>) -> Void) -> SelfEn uso:
request.responseData { response in switch response.result { case .success(let data): do { let asJSON = try JSONSerialization.jsonObject(with: data) // Handle as previously success } catch { // Here, I like to keep a track of error if it occurs, and also print the response data if possible into String with UTF8 encoding // I can't imagine the number of questions on SO where the error is because the API response simply not being a JSON and we end up asking for that "print", so be sure of it print("Error while decoding response: "\(error)" from: \(String(data: data, encoding: .utf8))") } case .failure(let error): // Handle as previously error } }