ios - 在 Swift 中将 responseJSON 更新为 responseDecodable

标签 ios swift alamofire jsondecoder

我是 Swift 新手,我正在尝试升级一些旧的 Swift 代码。我收到以下警告:

'responseJSON(queue:dataPreprocessor:emptyResponseCodes:emptyRequestMethods:options:completionHandler:)' is deprecated: responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.


...在下面的代码中:
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()
        }
    }
}
如果我用 responseDecodable 替换 responseJSON,我会收到以下错误:

Generic parameter 'T' could not be inferred


我需要做什么来更新此代码?

最佳答案

Alamofire推荐使用responseDecodable()因为人们经常使用 responseJSON() ,然后得到 response.data , 并调用 JSONDecoder()在上面。所以这是对 JSONSerialization 的内部调用不求返回”。此外,由于 Codable 是"new"的,并且仍然有旧问题可用,人们可能会错过 Codable 功能。见 this topic在 Alamofire repo 。
所以如果你使用 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
        }
}

关于ios - 在 Swift 中将 responseJSON 更新为 responseDecodable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70789753/

相关文章:

ios - 在 badoo/Chatto 聊天文本上填充 api 数据时无法访问 alamofire 请求范围之外的模型对象数据

ios - 当应用程序在后台运行时 Alamofire 完成

html - 如何使 iFrame 在 iPhone 6 中响应

ios - Corona SDK : storyboard. gotoScene 效果

ios - 有视频 : After Peek and Pop (3D Touch) background keeps scrolling

ios - 从 View Controller 调用应用程序委托(delegate)方法

ios - XCode 9.0 "Jump to definition"上下文菜单经常挂起

swift - 我如何访问 Swift 的 REPL?

ios - 即使我的 iOS 设备中没有谷歌地图,“canOpenURL”也会返回 true?

ios - Alamofire 网络事件指示器未显示