我正在准备将存储在我的 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(token) 函数:
let api = API()
api.getToken(["username":"blah","password":"blah"]) { responseObject, error in
debugPrint("responseObject = \(responseObject!["token"])")
return
}...
谢谢!