我正在努力将存储在我的django-rest框架中的临时令牌保存起来以执行一些GET / POST请求。这是我的代码:
class API {
let apiBaseUrl = "https://myhost.tld"
func getToken(loginData: NSDictionary ,completionHandler: (NSDictionary?, NSError?) -> ()) {
makePOST(loginData, section: "api-token-auth", completionHandler: completionHandler)
}
func getList(tokenStr: String, completionHandler: (NSDictionary?, NSError?) -> ()) {
makeGET(tokenStr, section: "api/list", completionHandler: completionHandler)
}
func makePOST(login: NSDictionary, section: String, completionHandler: (NSDictionary?, NSError?) -> ()) {
Alamofire.request(.POST, "\(apiBaseUrl)/\(section)/", parameters: login as! [String : String])
.responseJSON { response in
switch response.result {
case .Success(let value):
completionHandler(value as? NSDictionary, nil)
case .Failure(let error):
completionHandler(nil, error)
}
}
}
func makeGET(token: String?=nil, section: String, completionHandler: (NSDictionary?, NSError?) -> ()) {
Alamofire.request(.POST, "\(apiBaseUrl)/\(section)/", headers: ["Authorization":"Token \(token)"])
.responseJSON { response in
switch response.result {
case .Success(let value):
completionHandler(value as? NSDictionary, nil)
case .Failure(let error):
completionHandler(nil, error)
}
}
}
}
所以当我创建一个对象类型API()时,我可以在调用getToken时查看返回的我的令牌,但我不知道如何存储它以将其传递给api.getList(令牌)函数:
let api = API()
api.getToken(["username":"blah","password":"blah"]) { responseObject, error in
debugPrint("responseObject = \(responseObject!["token"])")
return
}...
谢谢!
答案 0 :(得分:0)
请尝试以下代码:
let api = API()
api.getToken(["username":"blah","password":"blah"], { responseObject, error in
print("responseObject = \(responseObject!["token"])")
api.getList(responseObject!["token"], { responseObject, error in
}
)
})