且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-06-05 16:39:03

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
        }
}