如何解决Alamofire的responseJSON弃用警告并改用responseDecodable
解决Alamofire中responseJSON弃用警告,改用responseDecodable
问题描述
收到Alamofire弃用警告:
'responseJSON(queue:dataPreprocessor:emptyResponseCodes:emptyRequestMethods:options:completionHandler:)' is deprecated: responseJSON deprecated and will be removed in Alamofire 6. Use responseDecodable instead.
当前触发警告的代码:
let URL = "https://www.googleapis.com/youtube/v3/videos?id=\(videoId)&part=contentDetails&key=\(apiKey)" var duration = String() AF.request(URL).responseJSON { response in if let result = response.value as? [String : Any], let main = result["items"] as? [[String : Any]]{ for obj in main{ duration = (obj as NSDictionary).value(forKeyPath:"contentDetails.duration") as! String completionHandler(duration, nil) } } }
改写方案
使用responseDecodable需要先定义对应API返回结构的Codable模型,再重构请求代码:
1. 定义Codable数据模型
根据YouTube API返回的JSON结构,创建层级对应的模型:
// 外层响应模型 struct YouTubeVideoResponse: Codable { let items: [VideoItem] } // 视频条目模型 struct VideoItem: Codable { let contentDetails: ContentDetails } // 内容详情模型 struct ContentDetails: Codable { let duration: String }
2. 重构请求代码
替换responseJSON为responseDecodable,同时完善错误处理:
let urlString = "https://www.googleapis.com/youtube/v3/videos?id=\(videoId)&part=contentDetails&key=\(apiKey)" AF.request(urlString).responseDecodable(of: YouTubeVideoResponse.self) { response in switch response.result { case .success(let videoResponse): // 按原逻辑取第一个视频的时长(若需遍历所有条目可自行调整) if let targetItem = videoResponse.items.first { completionHandler(targetItem.contentDetails.duration, nil) } else { let noDataError = NSError(domain: "YouTubeAPI", code: -1, userInfo: [NSLocalizedDescriptionKey: "未获取到视频数据"]) completionHandler("", noDataError) } case .failure(let error): completionHandler("", error) } }
说明
- 模型属性名需与API返回的JSON字段完全匹配,若需自定义属性名,可通过
CodingKeys枚举映射。 - 原代码循环遍历
items并多次调用completionHandler,建议根据业务需求调整(如返回所有时长数组,或仅取第一个/最后一个条目)。 - 新增了错误分支处理,避免原代码中强制解包可能导致的崩溃,提升代码安全性。
内容的提问来源于stack exchange,提问作者Shrestha Ashesh
相关产品推荐
相关产品推荐

