我刚刚开始看看Mattt的美妙的新Alamofire swift网络库,不知道如何使用它与自定义标题。
代码我试图从AFNetworking转换为Alamofire是这样的:
let request = NSMutableURLRequest(URL: url) request.setValue(authorizationToken,forHTTPHeaderField:"Authorization")
根据官方文档,不建议修改会话配置:
This is not recommended for Authorization or Content-Type headers.
Instead,use URLRequestConvertible and ParameterEncoding,
respectively.
因此,用于授权的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回答不再有效。在新版本中,附加标题应该添加到NSURLSessionConfiguration的HTTPAdditionalHeaders属性
Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": authorizationToken]