如何使用Alamofire传递令牌值

时间:2018-10-08 15:45:27

标签: ios swift4 alamofire

我已成功使用Alamofire从我的API检索令牌,它是一个字符串。我想将令牌(字符串)放入另一个请求中,以从API中获取一些JSON数据。但是我不知道如何通过。

    var token = String()// global variable

    let parameters = [
       "username" : usernameLabel.text!,
       "password" : passwordLabel.text!
    ]

    Alamofire.request(.POST, requestString, parameters: parameters, encoding: .JSON, headers: headers)
    .responseJSON { response in switch response.result {

    case .Success(let JSON):
        print("Success with JSON: \(JSON)")

        let response = JSON as! NSDictionary

        //example if there is a token
        token = response.objectForKey("token") as! String?
        print(token)

    case .Failure(let error):
        print("Request failed with error: \(error)")
        }
    }

1 个答案:

答案 0 :(得分:0)

尝试以以下方式拨打电话:

var token = String()// global variable

let parameters = [
   "username" : usernameLabel.text!,
   "password" : passwordLabel.text!
]
let headers = [
   "Authorization" : String(format: "Bearer: @%", token)
]

Alamofire.request(.POST, requestString, parameters: parameters, encoding: .JSON, headers: headers)
.responseJSON { response in switch response.result {

case .Success(let JSON):
    print("Success with JSON: \(JSON)")

    let response = JSON as! NSDictionary

    //example if there is a token
    token = response.objectForKey("token") as! String?
    print(token)

case .Failure(let error):
    print("Request failed with error: \(error)")
    }
}