gpt4 book ai didi

ios - 如何从 POST json 获取数据

转载 作者:行者123 更新时间:2023-11-28 09:24:53 25 4
gpt4 key购买 nike

我正在创建一个登录页面,一旦用户输入用户名密码,数据就会发送到 API,如果输入的数据正确,则返回成功。如果结果成功,我需要获取服务器以这种形式返回的用户的用户 key :

{
"STATUS_DESC": "Success",
"STATUS_CODE": 1,
"email": "keshurai1024@gmail.com",
"api_token": "Mqbraok1zsdasdasd4j3m"
}

现在我需要存储这个 api token 。为此,我正在尝试这个功能,但它不起作用 -

@IBAction func signInBtnPressed(_ sender: Any) {

let email : String! = self.usernameField.text
let password : String! = self.passwordField.text

var request = URLRequest(url: URL(string: "\(URL_BASE)\(AUTH)\(LOGIN)")!)
request.httpMethod = "POST"
let postString = "email=\(email!)&&password=\(password!)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
print("cant run")
return
}

if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
print("\(email)")
print("\(password)")


}
else {
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
print("\(URL_BASE)\(AUTH)\(LOGIN)/?\(postString)")
Alamofire.request("\(URL_BASE)\(AUTH)\(LOGIN)/?\(postString)" , method : .post).responseJSON { response in
let result = response.result
if let dict = result.value as? Dictionary<String,AnyObject>
{
print(dict)
let userTOKEN = dict["api_token"] as! String
print(userTOKEN)
}

}
}
}
task.resume()
}

请告诉我我犯了什么错误,我该如何改正..

最佳答案

尝试将数据解析为 json:

 if let jsonData = data {
do {
let jsonResult = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [String : Any]
print(jsonResult)
print(jsonResult?["api_token"])

//Here we saving aoi_token to UserDefaults:
UserDefaults.standard.setValue(token, forKey: "api_token")
print("\(UserDefaults.standard.value(forKey: "api_token")!)")
} catch {
print("JSON Processing Failed")
}
}

要存储您的 api_token,您需要使用 UserDefaults:

UserDefaults.standard.setValue(token, forKey: "api_token")
print("\(UserDefaults.standard.value(forKey: "api_token")!)")

关于ios - 如何从 POST json 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45751244/

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