leo*_*019 0 authentication json swift alamofire
我有一个受保护的 api,我得到了它的用户名和密码。当我使用 Postman 时,我选择了“Basic Auth”类型,在正文中我有用户登录信息等参数。它工作得很好。
但是,我正在尝试使用 Alamofire 做同样的事情,但我无法获得正确的 JSON 返回值。这是我所做的:
// user auth
let param = ["mobile":"3", "password":"100200"]
let urlStr = "http://MyApi.com/api/login"
let url = URL(string: urlStr)
// api auth
let user = "apiUserName"
let password = "ApiAuthPassword"
var headers: HTTPHeaders = ["mobile":"001",
"password":"1111"]
if let authorizationHeader = Request.authorizationHeader(user: user, password: password) {
headers[authorizationHeader.key] = authorizationHeader.value
}
Alamofire.request(url!, headers: headers)
.responseJSON { response in
print(response.result.value)
if let value: AnyObject = response.result.value as AnyObject? {
//Handle the results as JSON
print(value)
let usertoken = JSON(value)
print(usertoken)
}
}
Run Code Online (Sandbox Code Playgroud)
这将返回零。有人可以帮助我如何使用 Alamofire 执行 Postman 方法。谢谢!
小智 7
let user = "your username"
let password = "your password"
let credentialData = "\(user):\(password)".data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))!
let base64Credentials = credentialData.base64EncodedString()
let headers = [
"Authorization": "Basic \(base64Credentials)",
"Accept": "application/json",
"Content-Type": "application/json" ]
//put slash before \ (base64Credentials)
Alamofire.request("place your url", method: .get, parameters: nil,encoding: URLEncoding.default, headers: headers) .responseJSON { response in
switch response.result {
case .success(_):
//your success code
}
case .failure(_):
//your failure code
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6514 次 |
| 最近记录: |