本文介绍了更新响应JSON以响应SWIFT中的可解码响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是SWIFT新手,我正在尝试升级一些旧的SWIFT代码。我收到以下警告:
‘responseJSON(queue:dataPreprocessor:emptyResponseCodes:emptyRequestMethods:options:completionHandler:)’ 已弃用:responseJSON已弃用,将在 Alamofire 6.改用responseDecodable。
.在以下代码中:
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() } } }如果我将responseJSON替换为responseDecodable,则会收到此错误:
无法推断泛型参数"T"
我需要做什么才能更新此代码?
推荐答案Alamofire推荐使用responseDecodable(),因为大家经常使用responseJSON(),然后获取response.data,对其调用JSONDecoder()。因此,这是对JSONSerialization的内在呼唤。此外,由于Codable是新的,而且仍然有旧的问题可用,所以人们可能会错过Coble功能。请参阅AlamoFire Repo上的this topic。 因此,如果您使用Codable,我建议尽可能使用responseDecodable()。
但是,您仍然可以通过检索Data而不进行转换来手动完成:
为此,请使用:
@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) -> Self使用中:
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 } }更多推荐
更新响应JSON以响应SWIFT中的可解码响应
发布评论