Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Alamofire with custom headers for POST request

I implemented a POST request with Alamofire with a custom header, because we work with OAuth2 and we have to send an access token in every request inside the header. In this case I have to use a custom header.

The access token value for the HTTP header field Authorization does not work for me. The server generates an error because the header information for OAuth with the access token is not available.

But what is the mistake in my code?

Here is my current code:

let URL =  NSURL(string: url + "/server/rest/action")
var mutableURLRequest = NSMutableURLRequest(URL: URL!)
mutableURLRequest.setValue("Bearer \(accessToken)", forHTTPHeaderField: "Authorization")

//this method does not work anymore because it returns an error in the response
//Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = ["Authorization": "Bearer \(accessToken)"]

Alamofire.Manager.sharedInstance
    .request(.POST, mutableURLRequest, parameters: parameters, encoding: .JSON)
    .validate()
    .responseJSON {
                (request, response, data, error) -> Void in

                NSLog("REQUEST: \(request)")
                NSLog("RESPONSE: \(response)")
                NSLog("DATA: \(data)")
                NSLog("ERROR: \(error)")
    }
like image 307
Karl Avatar asked Feb 15 '15 13:02

Karl


People also ask

How do I pass the header in Alamofire?

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.

How do I use Alamofire in SwiftUI?

Adding Alamofire Into Our ProjectLaunch a new Xcode, SwiftUI based project and add the Alamofire dependency. You can use Cocoapods, Swift Package Manager or Carthage, whichever works the best for you. Once that's done, simply import Alamofire into your Swift class.

Can you use Alamofire Objective C?

Since in Objective-c, it is not possible to trigger the alamofire request, we have to trigger it in the wrapper and then send the response back to the calling object.


2 Answers

Here's an example of how I use it with custom headers:

    var manager = Manager.sharedInstance
    // Specifying the Headers we need
    manager.session.configuration.HTTPAdditionalHeaders = [
        "Content-Type": "application/x-www-form-urlencoded",
        "Accept": "application/vnd.lichess.v1+json",
        "X-Requested-With": "XMLHttpRequest",
        "User-Agent": "iMchess"
    ]

Now whenever you make a request, it'll use the specified headers.

Your code refactored: remember to import Alamofire

    let aManager = Manager.sharedInstance
    manager.session.configuration.HTTPAdditionalHeaders = [
        "Authorization": "Bearer \(accessToken)" ]

    let URL =  url + "/server/rest/action"

    request(.POST, URL, encoding: .JSON)
        .responseJSON {
            (request, response, data, error) -> Void in

            println("REQUEST: \(request)")
            println("RESPONSE: \(response)")
            println("DATA: \(data)")
            println("ERROR: \(error)")
    }

This is request signature request(method: Method, URLString: URLStringConvertible>, parameters: [String : AnyObject]?, encoding: ParameterEncoding)

As you can see you don't have to pass an NSURL in it, just the string of the URL, Alamofire takes care of the rest.

like image 77
leonardo Avatar answered Oct 12 '22 08:10

leonardo


There is a simple solution to send parameters and header with a single Alamofire request for Swift 3 and Alamofire 4.0

    let url = "myURL"
    let parameters: Parameters = [
        "param1": "hello",
        "param2": "world"
    ]
    let headers = [
        "x-access-token": "myToken",
    ]

    Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
        if response.result.isFailure {
            //In case of failure
        }else {
            //in case of success
        }
    }
like image 5
Kevin ABRIOUX Avatar answered Oct 12 '22 09:10

Kevin ABRIOUX