如何将Alamofire与自定义标头一起使用 [英] how to use Alamofire with custom headers
问题描述
我只是开始看一下Mattt出色的新型Alamofire快速联网库,还不确定如何将其与自定义标头一起使用。
I am just starting to take a look at Mattt's wonderful new Alamofire swift networking library and am not quite sure how one would use it with custom headers.
我要从AFNetworking转换为Alamofire的代码是:
The code i am trying to convert from AFNetworking to Alamofire is this:
let request = NSMutableURLRequest(URL: url)
request.setValue(authorizationToken, forHTTPHeaderField:"Authorization")
推荐答案
根据官方文档,不建议修改会话配置:
According to the official documentation, modifying the session configuration is not recommended:
不建议将其用于Authorization或Content-Type标头。
分别使用URLRequestConvertible和ParameterEncoding,
。
This is not recommended for Authorization or Content-Type headers. Instead, use URLRequestConvertible and ParameterEncoding, respectively.
因此使用URLRequestConvertible进行授权的示例是:
So an example usage of URLRequestConvertible for authorization would be:
enum Router: URLRequestConvertible {
static let baseUrlString = "some url string"
case Get(query: String)
var URLRequest: NSMutableURLRequest {
let (path: String, parameters: [String: AnyObject]?) = {
switch self {
case .Get(let query):
return ("/get", ["q": query])
}
}()
let URL = NSURL(string: Router.baseUrlString)!
let URLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
// set header fields
URLRequest.setValue("a", forHTTPHeaderField: "Authorization")
let encoding = Alamofire.ParameterEncoding.URL
return encoding.encode(URLRequest, parameters: parameters).0
}
}
,当您要提出请求时:
Manager.sharedInstance.request(Router.Get(query: "test"))
有关URLRequestConvertible的更多信息: https://github.com/Alamofire/Alamofire#urlrequestconvertible
More info about URLRequestConvertible: https://github.com/Alamofire/Alamofire#urlrequestconvertible
从Alamofire v1.0开始,Pers答案不再有效。在新版本中,应将其他标头添加到 NSURLSessionConfiguration
As of Alamofire v1.0 Pers answer no longer works. In the new version additional headers should be added to the HTTPAdditionalHeaders
property of NSURLSessionConfiguration
Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": authorizationToken]
此处的更多信息: https://github.com。 com / Alamofire / Alamofire / issues / 111
这篇关于如何将Alamofire与自定义标头一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!