Setting Custom Http Headers in Alamofire in iOS 7 Not Working

Alamofire custom header not working

You have to pass Alamofire a NSMutableURLRequest with your customized header. Check out this issue for a better explanation.

        var request = NSMutableURLRequest(URL: NSURL(string: "YOUR URL HERE")!)
request.HTTPMethod = "GET"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
request.addValue("application/vnd.dribbble.v1.text+json", forHTTPHeaderField: "Accept")
//Add paramaters (Optional)
let param = ["foo": "bar"]
let encoding = Alamofire.ParameterEncoding.URL
(request, _) = encoding.encode(request, parameters: param)
Alamofire.request(request).responseJSON { response in
//DO SOMETHING WITH YOUR RESPONSE OBJECT
}

Hope this helps :)

how to use Alamofire with custom headers

According to the official documentation, modifying the session configuration is not recommended:

This is not recommended for Authorization or Content-Type headers.
Instead, use URLRequestConvertible and ParameterEncoding,
respectively.

So an example usage of URLRequestConvertible for authorization would be:

enum Router: URLRequestConvertible {
static let baseUrlString = "some url string"

case Get(query: String)

var URLRequest: NSMutableURLRequest {
let (path: String, parameters: [String: AnyObject]?) = {
switch self {
case .Get(let query):
return ("/get", ["q": query])
}
}()

let URL = NSURL(string: Router.baseUrlString)!
let URLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
// set header fields
URLRequest.setValue("a", forHTTPHeaderField: "Authorization")

let encoding = Alamofire.ParameterEncoding.URL
return encoding.encode(URLRequest, parameters: parameters).0
}
}

and when you want to make a request:

Manager.sharedInstance.request(Router.Get(query: "test"))

More info about URLRequestConvertible: https://github.com/Alamofire/Alamofire#urlrequestconvertible

Old Answer

As of Alamofire v1.0 Pers answer no longer works. In the new version additional headers should be added to the HTTPAdditionalHeaders property of NSURLSessionConfiguration

Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": authorizationToken]

More info here: https://github.com/Alamofire/Alamofire/issues/111

Why is not recommended to modify session configuration for authorization headers in Alamofire?

There are a couple of reasons why we recommend this.

  1. The session configuration headers should only be set for those that are not going to change throughout the lifecycle of the session such as Accept-Encoding, Accept-Language, User-Agent, etc. If you need to set a header that could possibly change between requests, then you should add that header to the NSURLRequest itself which takes precedence over the session configuration headers.

  2. Modifying the session's configuration headers after the configuration has been created does not behavior consistently between iOS 7 and iOS 8. See this thread for more info.

Hopefully that helps clear things up a bit.

Authorization Header not setting in Alamofire 5?

After setting the Authorization header in your URLRequest:

urlRequest.addValue("\(APIConstants.API.token.rawValue) \(token.key)", forHTTPHeaderField: "Authorization")

then you override all the request's headers by setting headers property:

urlRequest.headers = headers

A nice solution would be to update the headers that you already created above, like this:

var headers: HTTPHeaders = [
.contentType(APIConstants.ContentType.json.rawValue),
.accept(APIConstants.ContentType.json.rawValue),
]

if let token = token {
headers.add(.authorization("\(APIConstants.API.token.rawValue) \(token.key)"))
}

urlRequest.headers = headers


Related Topics



Leave a reply



Submit