Swift Alamofire Adds a Custom Header to All Requests

I tried to add a custom header using this:

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

But this does not work, what am I doing wrong?

I need to add this after login so that the header is used in all requests.

+5
source share
4 answers

I do not know where you are doing this, but my AlomoFire requests look like this:

  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 } 

I assume you can put your header information in this header array

+4
source

I am tired of trying to manually replace the entire application by adding headers to 100+ of my queries. I chose a more lazy approach:

Make 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 in your xcode project, search for sharedInstance.request or whatever you do to execute the requests (all my code follows this pattern) and replace it with sharedInstance.myRequest (do not change the extension of sharedInstance.request itself) and voila:

Globally modified custom header for all requests!

If you want to add custom keys, you can add methods using the replace method, for example sharedInstance.request (method: ...) to sharedInstance.myRequest (customKeys: ..., method: ...) if you need custom variables .

+2
source

You should not add Authorization headers in this way. They should always be added using the headers parameter in the request method, as shown in @Glenn's article.

In addition, if you need to add other headers to the configuration, you need to create a custom configuration, set the header values, and then create a new Manager instance with the new configuration. Adding headers to the configuration after it has already been used to create the URL session results in undefined behavior depending on which version of the operating system you are running. We have many tests at Alamofire demonstrating this different behavior.

+1
source

Another (possibly more elegant) way to do this is to use the RequestAdapter as a demo on Alamofire github README

+1
source

Source: https://habr.com/ru/post/1232174/


All Articles