【问题标题】:How to pass token value with Alamofire如何使用 Alamofire 传递令牌值
【发布时间】:2023-12-27 17:14:01
【问题描述】:

我正在使用 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)")
        }
    }

【问题讨论】:

  • "Authorization": "Bearer \(token)" 是典型的身份验证标头..

标签: ios swift4 alamofire


【解决方案1】:

尝试拨打电话:

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)")
    }
}

【讨论】: