从alamofire返回令牌字符串

时间:2016-06-08 17:24:08

标签: ios swift alamofire swifty-json django-rest-auth

我正在努力将存储在我的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
}...

谢谢!

1 个答案:

答案 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
      }
    )
    })