Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
swift 4:无法解析JSON响应_Swift_Alamofire_Swifty Json - Fatal编程技术网

swift 4:无法解析JSON响应

swift 4:无法解析JSON响应,swift,alamofire,swifty-json,Swift,Alamofire,Swifty Json,我对Swift和IOS开发非常陌生 我正在使用Alamofire和SwityJSON发布到API端点进行身份验证,我故意输入错误的凭据来为用户编写指示代码 Alamofire.request(API_URL, method: .post, parameters: parameters) .responseJSON { response in if response.result.isSuccess {

我对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)")
            }
        }
printrspJSON的输出是

{msg:无效凭据}

因此,我希望if JSONmsg.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)
                }
            }
        }
}

没有错误,但也没有警报。。。我必须导入一些东西才能使用NSDictionary吗?当前我正在导入import UIKit import Firebase import Alamofire import SwiftyJSON请将API的响应也从消息=无效凭据更改为消息=无效凭据我在声明下添加了printres,并收到{msg=无效凭据;}