在 Swift 中将responseJSON更新为responseDecodable

the*_*ude 21 ios swift alamofire jsondecoder

我是 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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我用responseDecodable替换responseJSON,我会收到以下错误:

无法推断通用参数“T”

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

Lar*_*rme 37

Alamofire建议使用,responseDecodable()因为人们经常使用responseJSON(),然后获取response.data,并JSONDecoder()对其进行调用。JSONSerialization所以这是内心深处对“无”的呼唤。此外,由于 Codable 是“新的”,并且仍然存在旧问题,人们可能会错过 Codable 功能。请参阅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
Run Code Online (Sandbox Code Playgroud)

正在使用:

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
        }
}
Run Code Online (Sandbox Code Playgroud)

  • @smileBot 请随意评论他们的存储库,我提供了讨论链接(可能已关闭),但您可以就此提出问题。 (4认同)
  • 这种改变实际上没有多大意义。如果您确实需要将其转换为字典,那么您现在需要执行与旧方法相同的操作。我勒个去。 (2认同)
  • 谢谢,将使用responseData +手动反序列化。这种贬低真的很烦人。 (2认同)

Und*_*dog 5

AF.request(apiURL).responseDecodable(of: User.self) { response in
   switch response.result {
   case let .success(data):
     onSuccess(data)
   case let .failure(error):
     onError(error)
    }
   }
Run Code Online (Sandbox Code Playgroud)

这是我的“Alamofire”代码,“~> 5.6.2”