swift 4:无法解析 JSON 响应

杰格拉沃斯

我对 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)")
            }
        }

打印(rspJSON)的输出是

{“msg”:“无效的凭据”}

所以我希望 if JSON(msg.self) == "Invalid Credentials" 条件会命中,但显然这不是因为 print() 语句的输出可见并且看不到警报。

任何建议将不胜感激。

雅利安·夏尔马

在解析你的 JSON 时,总是在字典中找到响应的键。就像在这种情况下,您想要 'msg' 的值,您必须使用解析

if let message = res["msg"] as? 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)
                }
            }
        }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章