如何使用标头从服务器 Alamofire swift 获取数据
Posted
技术标签:
【中文标题】如何使用标头从服务器 Alamofire swift 获取数据【英文标题】:How to get data from server Alamofire swift with header 【发布时间】:2018-12-28 05:12:45 【问题描述】:当我想使用 Alamofire
从服务器获取数据时,它显示了一些错误
@IBAction func profile(_ sender: Any)
print(AuthService.instance.authToken)
print(AuthService.instance.userEmail)
let BEARER_HEADER2 = [
"id":AuthService.instance.userEmail,
"Authorization":AuthService.instance.authToken
//"Content-Type": "application/json; charset=utf-8"
]
print(BEARER_HEADER2)
Alamofire.request("http://fiveorzero.ml/api/v1/user/user/profile",method: .get, parameters: nil,encoding:URLEncoding.default, headers: BEARER_HEADER2).responseJSON response in
switch response.result
case .success(let value):
let swiftyJson = JSON(value)
print(swiftyJson)
print("Khabbab")
case .failure(let error):
debugPrint(response.result.error as Any)
print ("error: \(error)")
$2y$10$CUWgHVpbt6oPUdBo7weofucUniXw9JZoIeWZ1hZiwAfymZASoNWyS 128 [“id”:“128”,“授权”:“$2y$10$CUWgHVpbt6oPUdBo7weofucUniXw9JZoIeWZ1hZiwAfymZASoNWyS”] 可选(Alamofire.AFError.responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(错误域 = NSCocoaErrorDomain 代码 = 3840 “字符 0 周围的值无效。” UserInfo = NSDebugDescription = 字符 0 周围的值无效。))) 错误:responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(Error Domain=NSCocoaErrorDomain Code=3840 "字符 0 周围的值无效。" UserInfo=NSDebugDescription=字符 0 周围的值无效))
【问题讨论】:
尝试用responseString
替换responseJSON
您是否以与服务器所需格式相同的格式传递标头?
是的服务器想要token和id
还是不行
["id": "128", "Authorization": "$2y$10$CUWgHVpbt6oPUdBo7weofucUniXw9JZoIeWZ1hZiwAfymZASoNWyS"]
找不到页面
【参考方案1】:
您可以像这样使用创建标题
let id = "your id"
let Authorization = "your ascess token"
let credentialData = "\(id):\(Authorization)".data(using: String.Encoding.utf8)!
let base64Credentials = credentialData.base64EncodedString(options: [])
let headers = ["Authorization": "Basic \(base64Credentials)"]
Alamofire.request("your url" , method : .post, parameters: parameters,
headers: headers)
.responseJSON response in
// do whatever you want here
switch response.result
case .failure(let error): break
// self.popupp(elrtdata : "Please try again latter.")
case .success(let responseObject):
【讨论】:
不起作用,它说身份验证令牌不匹配!但在邮递员中,我可以使用授权令牌和 id 访问我的用户个人资料【参考方案2】: Alamofire.request(URL, method: .get, encoding: JSONEncoding.default, headers: headers).responseJSON
response in
switch response.result
case .success(let value):
completionHandler(value as? Array, nil)//completionHandler(value as? NSDictionary, nil)
print(value)
case .failure(let error):
completionHandler(nil,(error as NSError?)!)
【讨论】:
以上是关于如何使用标头从服务器 Alamofire swift 获取数据的主要内容,如果未能解决你的问题,请参考以下文章
如何覆盖 Alamofire SessionManager 以修改响应以添加标头?
如何使用 Alamofire 为每个请求添加 auth 标头,如果响应为 401 则执行某些操作?