swift – 如何使用Alamofire与自定义标题

前端之家收集整理的这篇文章主要介绍了swift – 如何使用Alamofire与自定义标题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我刚刚开始看看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]

更多信息:https://github.com/Alamofire/Alamofire/issues/111

猜你在找的Swift相关文章