在 Swift 中将 responseJSON 更新为 responseDecodable

Update responseJSON to responseDecodable in Swift

我是 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()
        }
    }
}

如果我将 responseJSON 替换为 responseDecodable,我会收到此错误:

Generic parameter 'T' could not be inferred

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

Alamofire recommends to use responseDecodable() because people were often using responseJSON(), then get the response.data, and call a JSONDecoder() on it. So this was making inner call of JSONSerialization for "nothing". Also, since Codable is "new", and there were still old questions available, people could be missing the Codable feature. See 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
        }
}