Update responseJSON to responseDecodable in Swift(更新响应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中的可解码响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:更新响应JSON以响应SWIFT中的可解码响应


- Android - 拆分 Drawable 2022-01-01
- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01