我对Swift和IOS开发非常新......
我正在使用Alamofire和SwityJSON发布到API端点进行身份验证,我故意输入错误的凭据来为用户编写指示。
Alamofire.request(API_URL, method: .post, parameters: parameters)
.responseJSON {
response in
if response.result.isSuccess {
let rspJSON: JSON = JSON(response.result.value!)
if JSON(msg.self) == "Invalid Credentials" {
let alert = UIAlertController(title: "Error", message: "Those credentials are not recognized.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler:{(action) in self.clearLogin()}))
self.present(alert, animated: true, completion: nil)
}
else {
print(rspJSON)
}
}
else {
print("Error \(response)")
}
}
print(rspJSON)的输出是
{" msg" :"证书无效" }
所以我希望if JSON(msg.self)==" Invalid Credentials"条件会命中,但显然不是因为print()语句的输出是可见的,并且看不到警报。
任何建议都将不胜感激。
答案 0 :(得分:1)
在解析JSON时,总是在字典中找到响应中的键。就像在这种情况下,你想要'msg'的值,你必须使用
进行解析if let message = res["msg"] as? String {}
为? String将响应转换为预期的数据类型。
Alamofire.request(API_URL, method: .post, parameters: parameters).responseJSON {
response in
if let res = response.result.value as? NSDictionary {
if let message = res["msg"] as? String {
if message == "Invalid Credentials" {
let alert = UIAlertController(title: "Error", message: "Those credentials are not recognized.", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler:{(action) in self.clearLogin()}))
self.present(alert, animated: true, completion: nil)
}
}
}
}