问题描述
伙计们! 我的应用程序再次崩溃,我不知道该怎么做。有人可以帮忙吗?! 顺便说一句,我是初学者..我正在学习。请客气点。
AF.request(URL_USER_ADD,method: .post,parameters: body,encoding: JSONEncoding.default,headers: header).responseJSON { (response) in
switch response.result {
case .success(let result):
if let json = result as? Data {
guard let data = response.data else { return }
let json = JSON(data: data)
let id = json["_id"].stringValue
let color = json["avatarColor"].stringValue
let avatarName = json["avatarName"].stringValue
let email = json["email"].stringValue
let name = json["name"].stringValue
UserDataService.instance.setUserData(id: id,color: color,avatarName: avatarName,email: email,name: name)
completion(true)
} else {
completion(false)
debugPrint(response.result as Any)
检查错误的图像!
谢谢!
解决方法
您的应用没有崩溃。编译失败。
“switch
必须详尽无遗”表示您没有处理 response.result
的所有可能情况。因为您的代码片段不包含上下文,所以我只能根据我自己的经验和您提供的代码猜测 response.result
是一个 Swift Result<Data,Error>
。在这种情况下,除了 .success(_)
,您还必须处理 .failure(_)
switch response.result
{
case .success(let result):
// The code you already have - more on that in a bit
// The thing that's missing
case .failure (let error):
// Do something with error here that makes sense for your app
}
这是第一件事,但您也会遇到 JSON
未定义的错误。事实上,我在您的屏幕截图或代码片段中没有看到它的定义,但也许它(或您打算参考的类似内容)是在我所见之外定义的。
如果它在您使用的框架(或 Swift 包)中,请确保在文件顶部 import
该框架。或者您是否打算使用 Foundation
JSON 转换工具(JSONSerialization
或 JSONDecoder
)?
附录
根据评论中的对话,我认为这就是你想要做的:
switch response.result
{
case .success(let result):
guard let json = try? JSON(data: result) else { fallthrough }
let id = json["_id"].stringValue
let color = json["avatarColor"].stringValue
let avatarName = json["avatarName"].stringValue
let email = json["email"].stringValue
let name = json["name"].stringValue
UserDataService.instance.setUserData(id: id,color: color,avatarName: avatarName,email: email,name: name)
completion(true)
case .failure(let error)
completion(false)
debugPrint(response.result as Any)
}
,
第一张截图是老师代码: enter image description here
第二个是我的,因为我拒绝将错误作为响应属性: enter image description here