Swift Alamofire为所有请求添加自定义标头

时间:2015-09-24 09:36:42

标签: swift header alamofire

我尝试添加自定义标头:

let manager = Manager.sharedInstance
manager.session.configuration.HTTPAdditionalHeaders = [
    "Authorization": "Token \(token)"
]

但它不起作用,我做错了什么?

我需要在登录后添加此项,以便在所有请求中使用该标头。

4 个答案:

答案 0 :(得分:3)

我不知道你在哪里做,但我的AlomoFire请求看起来像:

select f.*
from foo f
where not exists (select 1 from bar b where f.id = b.fooid);

我的猜测是你可以将标题信息放入标题数组

答案 1 :(得分:2)

我厌倦了尝试通过向我的100多个请求添加标题来手动替换整个应用程序。我选择了更懒惰的方法:

制作AlamofireManagerExtension.swift并使用以下代码:

import Foundation
import Alamofire

extension Manager {
    public func myRequest(
        method: Alamofire.Method,
        _ URLString: URLStringConvertible,
        parameters: [String: AnyObject]? = nil,
        encoding: ParameterEncoding = .URL,
        headers: [String: String]? = ["MY-STATIC-API-KEY" : "BLAHBLAHBLAH"])
        -> Request
    {
        return Manager.sharedInstance.request(
            method,
            URLString,
            parameters: parameters,
            encoding: encoding,
            headers: headers
        )
    }
}

然后,在你的xcode项目上使用ctrl-shift-f,搜索sharedInstance.request或你做的任何事情(我的所有代码都遵循这种模式)并用sharedInstance.myRequest替换它(确保不要更改扩展本身的sharedInstance.request)和瞧:

全局更改了所有请求的自定义标头!

如果你想添加自定义键,当然你可以使用替换方法预先添加方法 sharedInstance.request(method:...)到sharedInstance.myRequest(customKeys:...,method:...),如果你需要自定义变量。

答案 2 :(得分:2)

执行此操作的方法是在Alamofire advanced usage documentation上使用RequestAdapter进行演示。

答案 3 :(得分:1)

您不应以这种方式附加Authorization标头。应始终使用headers方法中的request参数附加它们,如@Glenn所示。

此外,如果需要将其他标头附加到配置,则需要创建自定义配置,设置标头值,然后使用新配置创建新的Manager实例。在已经用于创建URL会话之后将标头添加到配置会导致未定义的行为,具体取决于您运行的操作系统的版本。我们在Alamofire进行了许多测试,证明了这种不同的行为。