【发布时间】:2019-11-01 18:09:55
【问题描述】:
嗨,我是 swift 的新手,我还在学习,所以我尝试制作登录控制器并解析 json 数据,如果它更正它会解析带有 id 和内容的 json 数据,如果登录失败,那么 json 将显示有点信息。我已经为所有需要的值数据创建了一个结构,但是我得到了这个错误,它说它是 nil。
所以,如果登录成功,这是json:
[ { “身份证”:891, “名称”:“用户”, “电子邮件”:“qdpim@immobisp.com”, “状态”:“1” } ]
如果登录失败,这是json:
[ { "message": "登录失败..", “状态”:“0” } ]
所以基本上我猜它有一个相同的网址?但我不知道我有点卡在这里,我需要帮助
struct login : Codable {
let id : Int
let name : String
let email : String
let status : String
let message : String
init(dictionary : [String : Any]) {
id = (dictionary ["id"] as? Int)!
name = (dictionary ["name"] as? String)!
email = (dictionary ["email"] as? String)!
status = (dictionary ["status"] as? String)!
message = (dictionary ["message"] as? String)!
}
enum CodingKeys : String, CodingKey {
case id = "id"
case name = "name"
case email = "email"
case status = "status"
case message = "message"
}
}
func Login() {
let Email = EmailField.text!
let Pass = PasswordField.text!
print(api)
guard let JsonUrl = URL(string: api) else {return}
URLSession.shared.dataTask(with: JsonUrl) { (data, response, error) in
guard let data = data else {return}
do{
let parsing = try JSONDecoder().decode([login].self, from: data)
print(parsing)
self.Loginnn = parsing
let stats = self.Loginnn.map { $0.status}
if stats.contains("1"){
print("Login Success")
DispatchQueue.main.async {
self.appDelegate.loginSeque()
}
}else if stats.contains("0") {
let action = UIAlertAction(title: "Got It", style: .default, handler: nil)
let alert = UIAlertController(title: "Wrong Email / Password", message: "Please Try Again ", preferredStyle: .alert)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
// so basicly i wanna run this alert action by search status if its contains "0"
}
}
}catch{
print(error)
}
}.resume()
}
所以当我尝试测试登录失败时,我没有在我的日志中显示我的 json 中的消息,而是显示此错误
"keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "索引 0", intValue: 0)], debugDescription: "没有与键关联的值 CodingKeys(stringValue: \"id\", intValue: nil) (\"id\").", 底层错误:nil))"
我只是想在登录失败时弹出一些消息或警报,因为密码或电子邮件错误.....所以也许有人可以帮助我如何以最好的方式做到这一点?
【问题讨论】:
-
是的,我的 json id 是:Int not string