如何使用Alamofire在iOS中传递访问令牌

时间:2019-03-13 20:12:35

标签: swift xcode api jwt alamofire

我在登录时从API获取访问令牌,但是我不知道如何通过必须包含此令牌的所有接口传递令牌,以基于用户令牌从API检索数据。

此处用于登录的View Controller

@IBAction func login(_ sender: UIButton) {
        //getting the username and password
        let parameters: Parameters=[
        "name":userText.text!,
        "password":passwordTet.text!
        ]
        var token = String()// global variable
        let headers = [
            "Authorization" : String(format: "Bearer: @%", token)
        ]
    
        Alamofire.request(URL_USER_LOGIN, method: .post, parameters: parameters, headers: headers).responseJSON
            {
                response in
        print(response)

                //getting the json value from the server
                        if let result = response.result.value {
                            let jsonData = result as! NSDictionary

                           // if there is no error
                            if((!(jsonData.value(forKey: "error") != nil) )){
                                // if there is a token
                                token = (jsonData.object(forKey: "access_token") as! String?)!
                                print(token)
                                                
                                       //switching the screen
                      let Home_AdminViewController = self.storyboard?.instantiateViewController(withIdentifier: "TabBarViewController") as! TabBarViewController
                    self.navigationController?.pushViewController(Home_AdminViewController, animated: true)
                          self.dismiss(animated: false, completion: nil)
                        }
                            else {
                                //error message in case of invalid credential
                                self.LabelMessage.text = "Invalid username or password"
                            }

                }
        }

,这里的视图控制器示例必须使用与登录时生成的令牌相同的令牌,才能从API检索用户的数据,但是我不知道该怎么做 你能帮我吗?

var newOfferArray = [AnyObject]()
    override func viewDidLoad() {
        super.viewDidLoad()
        //Send request to API
        Alamofire.request("http://127.0.0.1:8000/api/offers").responseJSON { response in

            print(response)
            let result = response.result
            if let dict  = result.value  as? Dictionary<String,AnyObject>{
            if let innerdict = dict ["data"] {
                    self.newOfferArray = innerdict as! [AnyObject]
                    print(self.newOfferArray)
                    self.tableView.reloadData()
                }
            }
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return newOfferArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath ) as? Child1TableViewCell
        if self.newOfferArray.count > 0{
            //variables
            let name = self.newOfferArray[indexPath.row]
            cell?.Namelabel.text = name["name"] as? String

        }
       

        return cell!
    }

4 个答案:

答案 0 :(得分:0)

您可以使用静态变量创建简单的结构,例如:

struct Credentials {
    static var token: String?
    static var refreshToken: String?
}

您可以致电:Credentials.tokenCredentials.refreshToken

或者简单地,在一个空的swift文件中,添加没有任何类或结构的变量:

var token: String?
var refreshToken: String?

在这种情况下,您可以在任何文件中直接访问token

答案 1 :(得分:0)

您可以尝试以下代码

let auth = "your token"
let authData = auth.data(using: String.Encoding.utf8)!
let base64EncodedCredential = authData.base64EncodedString()
let authString = "Basic \(base64EncodedCredential)"
let authorization = ["Authorization" : authString]

在某些文件中使上层代码常量为全局

Alamofire.request(url, method: .get, parameters: para, encoding: URLEncoding.default, headers: authorization).responseSwiftyJSON { (result) in
      print("url:=",url)
      print("parameter:=",para)
      print("response:=",result.value ?? "nil")
      completion(result.result)
}

答案 2 :(得分:0)

您可以查看Alamofire中有关RequestAdatper的文档,我想这就是您想要的。

class AccessTokenAdapter: RequestAdapter {
    private let accessToken: String

    init(accessToken: String) {
        self.accessToken = accessToken
    }

    func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
        var urlRequest = urlRequest

        if let urlString = urlRequest.url?.absoluteString, urlString.hasPrefix("https://httpbin.org") {
            urlRequest.setValue("Bearer " + accessToken, forHTTPHeaderField: "Authorization")
        }

        return urlRequest
    }
}
let sessionManager = SessionManager()
sessionManager.adapter = AccessTokenAdapter(accessToken: "1234")

sessionManager.request("https://httpbin.org/get")

答案 3 :(得分:0)

谢谢大家!我使用Keychainwrapper库https://github.com/jrendel/SwiftKeychainWrapper

得到了答案

首先,我将访问令牌保存在登录请求中,然后可以在任何地方使用。