我只是开始看一下Mattt出色的新Alamofire快速联网库,并且不确定如何将其与自定义标头一起使用。
我正在尝试从AFNetworking转换为Alamofire的代码是这样的:
let request = NSMutableURLRequest(URL: url) request.setValue(authorizationToken, forHTTPHeaderField:"Authorization")
根据官方文档,不建议修改会话配置:
不建议将其用于Authorization或Content- Type标头。而是分别使用URLRequestConvertible和ParameterEncoding。
因此,URLRequestConvertible用于授权的示例用法是:
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
从Alamofire v1.0开始,Pers答案不再有效。在新版本中,应将附加标头添加到的HTTPAdditionalHeaders属性中NSURLSessionConfiguration
HTTPAdditionalHeaders
NSURLSessionConfiguration
Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": authorizationToken]
更多信息在这里:https : //github.com/Alamofire/Alamofire/issues/111