Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Custom HTTP Headers in Alamofire in iOS 7 not working

I've tried to set the Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders with my custom HTTP Headers in iOS 7 but I have had no luck.

This works fine in iOS 8.

Does anyone have any suggestions?

like image 201
user2362696 Avatar asked Nov 06 '14 16:11

user2362696


3 Answers

I got it working.

This has no effect on iOS7:

Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["CustomHeader": customValue]

This however will work on both iOS7 & 8:

var headers = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders ?? [:]
    headers["CustomHeader"] = customValue

    let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.HTTPAdditionalHeaders = headers

    Alamofire
        .Manager(configuration: configuration)
        .request(.GET, "https://example.com/api/users", parameters: nil, encoding: .JSON)
like image 143
Andreas Du Rietz Avatar answered Oct 21 '22 18:10

Andreas Du Rietz


I get stuck with the same problem, at the end I come up with the wolfing solution. (I changed a little bit the originally library, so be carefull!)

I was always calling the method:

public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request

And I noticed the call to the method:

private func URLRequest(method: Method, URL: URLStringConvertible) -> NSURLRequest

Just inside this function i inserted one line of code:

mutableURLRequest.setValue(valueHeader, forHTTPHeaderField: keyHeader)

with the following result (just to be clear):

private func URLRequest(method: Method, URL: URLStringConvertible) -> NSURLRequest {
    let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL.URLString)!)
    mutableURLRequest.HTTPMethod = method.rawValue

    if(contentHeader){
        mutableURLRequest.setValue(valueHeader, forHTTPHeaderField: keyHeader!)
    }

    return mutableURLRequest
}

I created also a method to pass the values. I hope this will work

like image 1
Antonio Romano Avatar answered Oct 21 '22 18:10

Antonio Romano


I'm using the NSMutableURLRequest to set custom headers.

Check this example.

var request = NSMutableURLRequest(URL: NSURL(string: "http://example.com")!)
request.HTTPMethod = "POST"
request.setValue("<HEADER VALUE>", forHTTPHeaderField: "<HEADER FIELD>")

var parameter: NSDictionary = ["dimensions" :["product" : ["name" : "macpro", "price" : "350"]]]
 request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameter, options: nil, error: nil)

Alamofire.request(request).response { (request, response, result, error) -> Void in
                // handle response
     println("\(request) \t \(response) \t \(result) \t \(error) ")
}
like image 1
Lucas Torquato Avatar answered Oct 21 '22 18:10

Lucas Torquato