I tried to add custom header with this:
let manager = Manager.sharedInstance
manager.session.configuration.HTTPAdditionalHeaders = [
\"Authorization\": \
You should not append Authorization
headers in this way. They should always be appended using the headers
parameter in the request
method as shown by @Glenn.
Additionally, if you need to append other headers to a configuration, you need to create a custom configuration, set the header values, then create a new Manager
instance with the new configuration. Adding headers to a configuration after it has already been used to create a URL session results in undefined behavior depending on which version of which OS you are running on. We have many tests in Alamofire demonstrating this varying behavior.
I got tired trying to manually replace the whole app by adding headers to 100+ of my requests. I opted for a more lazier approach:
Make an AlamofireManagerExtension.swift and use the following code:
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
)
}
}
Then, ctrl-shift-f on your xcode project, search for sharedInstance.request or whatever you do to make requests (all of my code follows this pattern) and replace it with sharedInstance.myRequest (Be sure not to change the extension itself's sharedInstance.request) and voila:
Globally changed custom header for all requests!
If you wanted to add in custom keys, of course you can prepend methods with the replace method like sharedInstance.request(method: ...) to sharedInstance.myRequest(customKeys: ..., method: ...) if you need custom variables.
I don't know where you do that but my AlomoFire requests look like :
Alamofire.request(.GET, urlPath, parameters: parameters, headers: ["X-API-KEY": apiKey, "Content-type application":"json", "Accept application" : "json"]).responseJSON() { (req,res, data, error) in //blah blah }
My guess is that you can put your header information into that headers array
A way to do this is to use a RequestAdapter as demoed on the Alamofire advanced usage documentation.