Swift使用Alamofire遇'isSuccess因internal保护级别无法访问'问题求助
解决Alamofire中
'isSuccess' is inaccessible due to 'internal' protection level的问题 嘿,这个问题我升级Alamofire版本后也踩过坑!原因很简单:Alamofire在新版本里把Result.isSuccess的访问级别设成了internal,外部代码自然没法直接调用它。不过别慌,几个简单的替代方案就能搞定:
方案1:用if case匹配成功状态,直接获取返回值
这种方式不仅能判断成功状态,还能直接拿到返回值,省去了强制解包的风险:
AF.request(jsonURL, method: .get, parameters: parameters).responseJSON { response in if case .success(let value) = response.result { print("Got the info") print(response) let flowerJSON: JSON = JSON(value) let list = flowerJSON["..."]["..."]["..."].stringValue print(list) } else if case .failure(let error) = response.result { // 顺手处理错误情况 print("请求失败:\(error.localizedDescription)") } }
方案2:用switch清晰处理所有状态
如果需要明确区分成功、失败的各种场景,switch语句会更直观:
AF.request(jsonURL, method: .get, parameters: parameters).responseJSON { response in switch response.result { case .success(let value): print("Got the info") print(response) let flowerJSON: JSON = JSON(value) let list = flowerJSON["..."]["..."]["..."].stringValue print(list) case .failure(let error): print("请求出错:\(error)") // 这里可以加用户提示、错误日志上报等逻辑 } }
方案3:直接用response.isSuccess判断
另外,Alamofire的DataResponse对象本身有个公开的isSuccess属性,也能直接用来判断请求是否成功:
AF.request(jsonURL, method: .get, parameters: parameters).responseJSON { response in if response.isSuccess { print("Got the info") print(response) // 记得安全解包,别用!强制解包哦 guard let value = response.result.value else { return } let flowerJSON: JSON = JSON(value) let list = flowerJSON["..."]["..."]["..."].stringValue print(list) } else { if let error = response.result.error { print("请求失败:\(error)") } } }
最后提醒一句:尽量别用!强制解包response.result.value,万一请求成功但返回值为空,直接就崩溃了,用guard let或者if let安全解包才是稳妥的做法。
内容的提问来源于stack exchange,提问作者Aboud Jbara
相关产品推荐
相关产品推荐

