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.
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 theNSURLRequest
itself which takes precedence over the session configuration headers.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
Core Data Taking Time to Insert Records with Fetching Entity & Set as Relationship
Get All List of Uiviewcontrollers in iOS Swift
Multiple Iboutlets in Same Line of Same Type in Swift
Cmpedometer Querypedometerdatafromdate Returns Error 103
Return in Function Without Return Value in Swift
Buttonwithtype' Is Unavailable: Use Object Construction 'Uibutton(Type:)
Uilocalnotification: Playing a Custom Audio File Saved in Documents Directory
What Is Correct Way to Notify View Controller from Appdelegate
Timer Label Not Updated After Switching Views (Swift)
Peek/Pop Preview Ignores Cell Corner Radius in Collection View
Include Pods in Main Target and Not in Watchkit Extension
How to Run My Performance Tests More Than Ten Times
Converting an Existing Project into Customizable Framework
How to Get Alexa Working on My iOS App
Setting a Stateobject Value from Child View Causes Navigationview to Pop All Views