gpt4 book ai didi

json - Swift 解析使用 1 个 url api 解码 2 个不同的 json

转载 作者:行者123 更新时间:2023-11-28 05:41:14 24 4
gpt4 key购买 nike

嗨,我是 swift 的新手,我还在学习,所以我尝试制作登录 Controller 并解析 json 数据,如果它更正它解析带有 id 和东西的 json 数据,如果登录失败则 json 将显示有点信息。我已经为所有需要的值数据创建了一个结构,但是我得到了一个错误,说它为零。

所以,如果登录成功,这是 json :

[ { "id": 891, "name": "User", "email": "qdpim@immobisp.com", "status": "1" } ]

如果登录失败,这是 json :

[ { "message": "Login Failed..", "status": "0" } ]

所以基本上它有一个相同的 url 我猜?但我不知道我有点卡在这里,我需要帮助

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: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"id\", intValue: nil) (\"id\").", underlyingError: nil))"

我只是想在登录失败时弹出一些消息或提醒,因为密码或电子邮件错误......所以也许有人可以帮助我如何以最好的方式做到这一点?

最佳答案

您可以如下声明成功和失败响应类型,

struct LoginSuccess: Decodable {
var id: Int
var name: String
var email: String
var status: String
}

struct LoginFailure: Decodable {
var status: String
var message: String
}

然后用作,

guard let JsonUrl = URL(string: api) else { return }
URLSession.shared.dataTask(with: JsonUrl) { (data, response, error) in
guard let data = data else { return }

if let success = try? JSONDecoder().decode([LoginSuccess].self, from: data).first {
GlobalVariable.UserId = String(success.id)
DispatchQueue.main.async {
self.appDelegate.loginSeque()
}
} else if let failure = try? JSONDecoder().decode([LoginFailure].self, from: data).first {
let action = UIAlertAction(title: "Got It", style: .default, handler: nil)
let alert = UIAlertController(title: "Wrong Email / Password", message: failure.message, preferredStyle: .alert)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}.resume()

关于json - Swift 解析使用 1 个 url api 解码 2 个不同的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56660272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com