swift 4: 无法解析 JSON 响应

swift 4: Unable to parse JSON response

我对 Swift 和 IOS 开发...

非常陌生

我正在使用 Alamofire 和 SwityJSON 到 post 到 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" : "Invalid Credentials" }

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

如有任何建议,我们将不胜感激。

在解析您的 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)
                }
            }
        }
}