如何将 Alamofire 与自定义标头一起使用 [英] how to use Alamofire with custom headers

查看:36
本文介绍了如何将 Alamofire 与自定义标头一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始研究 Mattt 的精彩新 Alamofire swift 网络库,我不太确定如何将它与自定义标头一起使用.

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
    }
}

以及当您想提出请求时:

and when you want to make a request:

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/Alamofire/Alamofire/issues/111

这篇关于如何将 Alamofire 与自定义标头一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆