【问题标题】:Return token string from alamofire从 alamofire 返回令牌字符串
【发布时间】:2016-06-08 17:24:08
【问题描述】:

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

谢谢!

【问题讨论】:

  • 您需要将令牌本地存储在您的设备中吗?
  • @Daniel 您可以将令牌存储在完成处理程序的变量中
  • 我可以存储在钥匙串中,但它更好地作为变量传递给下一个函数。如何将新变量放入完成处理程序并全局存储?

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


【解决方案1】:

试试下面的代码:

let api = API()
    api.getToken(["username":"blah","password":"blah"], { responseObject, error in
            print("responseObject = \(responseObject!["token"])")
            api.getList(responseObject!["token"], { responseObject, error in
      }
    )
    })

【讨论】:

  • 你的答案有效,但我必须继承更多的功能。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-19
  • 2018-07-18
  • 2023-01-02
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
  • 2018-10-21
相关资源
最近更新 更多