Search code examples
iosswifthttp-headersnsurlrequestalamofire

Adding headers to Alamofire request (with ephemeral session)


I'm trying to add headers into AlamoFire requests.

It works well when I use the following code:

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

However, when I need to user an ephemeral session it does not work with the following code.

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

Am I missing something?

Thanks in advance,


Solution

  • You have to ensure your manager is retained, you could do it by setting it as a stored property. You'll find more informations here: 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
            }
    }