更新响应JSON以响应SWIFT中的可解码响应

编程入门 行业动态 更新时间:2024-10-05 23:28:05
本文介绍了更新响应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中的可解码响应

本文发布于:2023-11-26 23:12:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635593.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:JSON   SWIFT

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!