Reputation: 1924
So I have an app that makes frequent requests to various endpoints on our API, and every request pretty much has the same custom headers sent with it. I'd like to know if there is a way to globally set custom header using NSURLSessionConfiguration, and if so...what is the syntax in Swift and where would I put it? AppDelegate? I've done some searching and can't seem to find a good example of this. Is it a bad practice? Not doable?
EDIT:
I'm using Alamofire for request/response, so I need something that sets them globally so that that library (and others that happen to use NSURLSession) will send the headers along by default.
Upvotes: 0
Views: 1468
Reputation: 16643
We have this documented right in the README.
var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
defaultHeaders["DNT"] = "1 (Do Not Track Enabled)"
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPAdditionalHeaders = defaultHeaders
let manager = Alamofire.Manager(configuration: configuration)
Then you need to use the new manager
instead of the global Alamofire
singleton.
manager.request(.GET, "https://httpbin.org/get")
.responseJSON { _, _, result in
debugPrint(result)
}
This will attach the DNT
header to every request that is sent through this manager
instance.
Each
Manager
instance has its own internalNSURLSession
which also has its own configuration. Therefore, this override only works for thisManager
instance. If you need these headers on a differentManager
instance, you'll have to set it up the same way.
Upvotes: 2