我是IOS开发世界的新手,我正在使用swift和Alamofire开发应用程序。我需要调用一个返回会话令牌的服务端点,以便登录我的应用程序:
Alamofire.request(.POST, url, parameters: ["grant_type": "password", "username": "myusername", "password": "mypassword"], encoding: .JSON).validate().responseString { response in
switch response.result {
case .Success:
onSuccess()
case .Failure(let error):
onError(error)
}
}
此Api通话的响应是成功的,但我总是得到{"错误":" unsupported_grant_type"}而不是获取令牌信息。
请建议。
答案 0 :(得分:1)
使用SwiftyJSON
和Alomofire
,我使用了它对我有用的功能:
let authTokenUrl = "http://0.0.0.0:8000/api/auth/token/"
func doAuth(username:String, password:AnyObject){
let params = ["username": username, "password": password]
let authToken = Alamofire.request(Method.POST, self.authTokenUrl, parameters: params)
self.activityLoader.startAnimating()
authToken.responseJSON{ response in
//print(response.request) // original URL request
//print(response.response) // URL response
//print(response.data) // server data
//print(response.result) // result of response serialization
switch response.result {
case .Success:
//print("Success!")
let statusCode = response.response!.statusCode
switch statusCode {
case 200...299:
//self.messageText.text = "Auth success!"
let jsonData = JSON(response.result.value!) //unwrap the data (because it was optional) & use SwiftyJSON
let token = jsonData["token"].string
let username = jsonData["user"].string!
let active = jsonData["active"].bool!
let userid = jsonData["userid"].int!
// si dessous c'est la correction
//let userid = jsonData["userid"].string!
if active {
self.keychain["token"] = token
self.keychain["username"] = username
self.keychain["userid"] = String(userid)
} else {
self.keychain["token"] = nil
}
self.getProjects()
case 400...499:
let jsonData = JSON(response.result.value!)
let errorArray = jsonData["non_field_errors"].array
if errorArray != nil {
var currentString = ""
for err in errorArray! {
currentString += "\(err)"
}
//print("Server responded no. \(currentString)")
Notification().notify("\(currentString)", delaySec: 2.5, inspeed: 0.5, outspeed: 1.0)
}
case 500...599:
//print("Server Error.")
Notification().notify("There was an error.", delaySec: 2.5, inspeed: 0.5, outspeed: 1.0)
default:
// print("There was an error with your request.")
Notification().notify("There was an error with your request.", delaySec: 2.5, inspeed: 0.5, outspeed: 1.0)
}
case .Failure(let error):
print("Request failed with error: \(error)")
}
}
self.activityLoader.stopAnimating()
}