how to use Alamofire with custom headers

89,357

Solution 1

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

Solution 2

For headers that change from request to request, you can pass them directly to the request method. From the docs:

Adding a custom HTTP header to a Request is supported directly in the global request method. This makes it easy to attach HTTP headers to a Request that can be constantly changing.

And the example given:

    let headers = [
        "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
        "Content-Type": "application/x-www-form-urlencoded"
    ]

    Alamofire.request(.GET, "https://httpbin.org/get", headers: headers)
             .responseJSON { response in
                 debugPrint(response)
             }

If, however, you wish to set headers that do not change, it is recommended that you do so on the NSURLConfiguration object, as others have mentioned here.

Solution 3

At this time , Swift 3.0 , Xcode 8.x, Alamofire 4.x:

You can use custom header as below:

let headers: HTTPHeaders = [
    "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
    "Accept": "application/json"
]

Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
    debugPrint(response)
}

For reference

Solution 4

I've created a static headers method in a separate APIManager class.

import Foundation
import Alamofire

class APIManager {

    class func headers() -> HTTPHeaders {
        var headers: HTTPHeaders = [
            "Content-Type": "application/json",
            "Accept": "application/json"
        ]

        if let authToken = UserDefaults.standard.string(forKey: "auth_token") {
            headers["Authorization"] = "Token" + " " + authToken
        }

        return headers
    }
}

And I use it in requests:

Alamofire.request(urlString,
                      method: .get,
                      headers:APIManager.headers())

Solution 5

NOTE: this was before 1.0. It no longer works, look at the accepted answer instead.


You use the defaultHeaders property on the Manager singleton to add headers, like this:

Alamofire.Manager.sharedInstance.defaultHeaders.updateValue(authorizationToken, forKey: "Authorization")

At least it works for me. :)

Share:
89,357
Rene Limberger
Author by

Rene Limberger

Updated on July 08, 2022

Comments

  • Rene Limberger
    Rene Limberger almost 2 years

    I am just starting to take a look at Mattt's wonderful new Alamofire swift networking library and am not quite sure how one would use it with custom headers.

    The code i am trying to convert from AFNetworking to Alamofire is this:

    let request = NSMutableURLRequest(URL: url)
    request.setValue(authorizationToken, forHTTPHeaderField:"Authorization")