我正在尝试发送电子邮件和passowrd并获得令牌作为回应。
使用相同的令牌我必须从服务器获得响应。
请帮助我,在这种情况下,我尝试了NSURL方法和almofire,但没有得到适当的outhput相同。
//Check Below code and give me proper output.
func NewsAPI(){
let url = "https://mastleadership.com/api/token-auth"
//Get token logic
let token = ""
let headers = ["Authorization": "token \(token)"]
let params = ["email": "kishor@kishor.com", "password":"abcd"] //This goes in the body of the request
Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.default, headers: headers).responseJSON { (response) in
if let value = response.result.value {
print(value)
}
}
}
答案 0 :(得分:0)
据我了解 - 您想发布带有参数的请求并接收令牌并再次使用相同的参数发布相同的请求?抱歉,但没有逻辑......但如果真的那么你想做什么,那么你必须做两次请求,并且在response.result上你必须保存对你的令牌变量的正确响应。
Buut ..无论如何如果你想接受令牌作为响应如果params(登录和密码)是正确的而不是保存它,那么你可以这样做(假设服务器的响应也是JSON):< / p>
登录请求:
func loginRestt(login:String, password:String){
let urlStr = "https://mastleadership.com/api/token-auth"
let params = ["login":login, "password":password]
let headers: HTTPHeaders = ["Content-Type": "application/json"]
Alamofire.request(urlStr, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
switch response.result {
case .success:
print("\(self.TAG), receiving response from login with \(response)")
guard let receivedResponse = try! JSONSerialization.jsonObject(with: response.data!, options: []) as? [String:Any] else {
print("\(self.TAG), Error parsing response from login for json")
return
}
//Here I get token and save it to preferences
if let token:String = receivedResponse["token"] as? String {
print("\(self.TAG), \(token)")
UserDefaults.standard.set(token, forKey: preferencesKeys.loginToken)
} else {
print("\(self.TAG), error receiving token")
return
}
case .failure(let error):
print("\(self.TAG), error receiving response for login with \(error)")
return
}
}
}
与需要令牌的任何其他请求相比,只需在标题中添加令牌,例如:
let token = UserDefaults.standard.value(forKey: preferencesKeys.loginToken)
let headers: HTTPHeaders = ["Authorization": "token \(token!)"]
RestService.shared.almgr.request(urlStr, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
switch response.result {
case .success:
//response received
case .failure(let error):
//problems
}