将 headers 添加到 Alamofire 请求(使用临时 session)

Adding headers to Alamofire request (with ephemeral session)

我正在尝试将 headers 添加到 AlamoFire 请求中。

当我使用以下代码时效果很好:

let manager = Manager.sharedInstance
manager.session.configuration.HTTPAdditionalHeaders = [
    "Authorization": "Bearer \(accessToken!)" ]

但是,当我需要使用临时 session 时,它不适用于以下代码。

let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
let manager = Manager(configuration: configuration)
manager.session.configuration.HTTPAdditionalHeaders = [
    "Authorization": "Bearer \(accessToken!)" ]

我是不是漏掉了什么?

提前致谢,

您必须确保保留您的经理,您可以通过将其设置为已存储的 属性 来做到这一点。您可以在此处找到更多信息:https://github.com/Alamofire/Alamofire/issues/157

let customManager: Manager?

init() {
    let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
    self.customManager = Manager(configuration: configuration)
    self.customManager!.session.configuration.HTTPAdditionalHeaders = [
    "Authorization": "Bearer \(accessToken!)" ]
}


func yourFunc() {
    let URL = NSURL(string: identityURL)
    var mutableURLRequest = NSMutableURLRequest(URL: URL!)

    let request = self.customManager!.request(mutableURLRequest)

    request.responseJSON {
        (request, response, data, error) in
        if let response = response {
             // Your code
        }
}
 func HTTPHeader(param : NSDictionary)
    {
        var username: AnyObject? = param[kAPIUsername]
        var password: AnyObject? = param[kAPIPassword]

        var str = "\(username!):\(password!)"

        let base64Encoded = BaseVC.sharedInstance.encodeStringToBase64(str)

        Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = [
            "Authorization": "Basic \(base64Encoded)",
        ]
    }


  func encodeStringToBase64(str : String) -> String
    {
        // UTF 8 str from original
        // NSData! type returned (optional)
        let utf8str = str.dataUsingEncoding(NSUTF8StringEncoding)

        // Base64 encode UTF 8 string
        // fromRaw(0) is equivalent to objc 'base64EncodedStringWithOptions:0'
        // Notice the unwrapping given the NSData! optional
        // NSString! returned (optional)
        let base64Encoded = utf8str!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))

        return base64Encoded;
    }


 func GET()
    {
        HTTPHeader(param, token: token)

        request(.GET, API URL , encoding: .JSON)
            .progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
                //progress

            }
            .responseJSON {

                (request, response, json, error) -> Void in

            //get response here 
        }
    }

可能对 link 有帮助:how to use Alamofire with custom headers