我已经为LoginViewController响应创建了模型。
我得到了如下的响应。如何在LoginViewController中向这个模式添加值,我得到了这个响应?
struct Employees: Codable {
let jsonrpc: String
let result: Result
}
// MARK: - Result
struct Result: Codable {
let userdata: Userdata
let token: String
}
// MARK: - Userdata
struct Userdata: Codable {
let id: Int
let fname, lname, email: String
.......
}
登录视图控制器API调用:
func loginService() {
let url = URL(string: "https://apkool.com")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let jsonpost = LoginData(jsonrpc: "2.0", params: (PostLogin(email: nameTf.text!, password: passwordTf.text!, device_id: "2")))
do {
let jsonBody = try JSONEncoder().encode(jsonpost)
request.httpBody = jsonBody
} catch {
print("Error while encoding parameter: \(error)")
}
let session = URLSession.shared
let task = session.dataTask(with: request) { [self] (data, response, error) in
guard let data = data else {return}
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]
print("the json output \(String(describing: json))")
let error = json!["error"] as? [String : Any]
let status = error?["status"] as? [String : Any]
DispatchQueue.main.sync {
if error != nil {
let controller = UIAlertController(title: "Alert", message: "Your email is not verified", preferredStyle: .alert)
let ok = UIAlertAction(title: "OK", style: .default, handler: nil)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
controller.addAction(ok)
controller.addAction(cancel)
self.present(controller, animated: true, completion: nil)
} else {
let res = json?["result"] as? [String : Any]
let uData = res?["userdata"] as? [String : Any]
var nameLogin = uData?["slug"] as? String
var emailLogin = uData?["email"] as? String
print("login name \(String(describing: nameLogin))")
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ProfileViewController1") as? ProfileViewController1
vc?.name = nameLogin
vc?.email = emailLogin
self.navigationController?.pushViewController(vc!, animated: true)
}
}
print("the error is \(error)")
} catch { print("Error while decoding: \(error.localizedDescription)") }
}
task.resume()
}
**我想添加登录响应到模型中,以便在另一个ViewController中使用这些值。**我在这里卡住了很长时间。请求帮助!
对于上述API,我在登录时得到以下响应:
{
"jsonrpc": "2.0",
"result": {
"userdata": {
"id": 47,
"fname": "sample",
"lname": "test",
"last_login": "2021-02-23 15:04:56",
"created_at": "2021-02-17 20:22:49",
"updated_at": "2021-02-23 15:04:56",
"deleted_at": null
},
"devicetoken": fasfcsdfdsfsdfsd
}
}
2条答案
按热度按时间mhd8tkvw1#
由于您可能会从服务器收到如下错误:
改变你的模型:
那么在你的API中
hsvhsicv2#
你可以试试这个模型,你可以解码你的数据如下。这里的数据是从你的guardlet语句的响应。