我正在创建一个登录页面,一旦用户输入用户名密码,数据就会发送到API,如果输入的数据正确,则返回成功。如果结果成功,我需要获取服务器在此表单中返回的用户的用户密钥:
{
"STATUS_DESC": "Success",
"STATUS_CODE": 1,
"email": "keshurai1024@gmail.com",
"api_token": "Mqbraok1zsdasdasd4j3m"
}
现在我需要存储这个api令牌。 为此,我正在尝试这个功能,但它无法正常工作 -
@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()
}
请告诉我我在做什么错误以及如何纠正它..
答案 0 :(得分:1)
尝试将数据解析为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")!)")
答案 1 :(得分:-2)
我不明白您使用URLSession
的原因。您可以使用Alamofire
作为URLSession
的包装。
@IBAction func signInBtnPressed(_ sender: Any) {
let email : String = self.usernameField.text ?? ""
let password : String = self.passwordField.text ?? ""
Alamofire.request("\(URL_BASE)\(AUTH)\(LOGIN)/",
method: .post,
parameters: ["email": email,
"password", password],
encoding: URLEncoding.httpBody).responseJSON { response in
if let dict = response.value as? [String: Any] {
let token = dict["api_token"] as! String
//store token
UserDefaults.standard.set(token, forKey: "token")
UserDefaults.standard.synchronize()
}
let savedToken = UserDefaults.standard.string(forKey: "token")
print(savedToken)
}
}