Kqtr
Kqtr

Reputation: 5935

Alamofire: syntax for writing a POST request with url, method, parameters, headers and encoding

I've had a look at tons of previous answers, but couldn't find an up-to-date one that includes ALL the following parameters: url, method, parameters, encoding, headers.

This:

Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { ... }

Gives the error: Extra argument "method" in call


UPDATE 26/06/2017

The format of the request is actually correct, the issue is that the format of one parameter sent was incorrect. The error is pretty misleading. See my answer below for a list of the parameter's types required and their default value.

Upvotes: 3

Views: 1247

Answers (2)

Kqtr
Kqtr

Reputation: 5935

Cristallo's answer is a great custom way to do it.

In the meantime, I've discovered that the request in my original question actually works, at the condition that the value passed to the parameter headers is of type [String: String].

Alamofire's error is a bit misleading:

Extra argument 'method' in call.

Here is therefore the request that can be used:

Alamofire.request(
        url,
        method: .post,
        parameters: params,
        encoding: JSONEncoding.default,
        headers: httpHeaders).responseJSON { response in
        ...
    }

With the parameters types expected and their default values (taken from Alamofire source code):

Alamofire.request(
    _ url: URLConvertible,
    method: HTTPMethod = .get,
    parameters: Parameters? = nil,
    encoding: ParameterEncoding = URLEncoding.default,
    headers: HTTPHeaders? = nil)

Upvotes: 2

cristallo
cristallo

Reputation: 2089

the easiest way is to create a specific request and then customize it using Request methods and properties

var request = URLRequest(url: yourUrl)
request.httpMethod = yourMethod 
request.setValue(yourCustomizedValue)
request.httpBody = yourBody
...

Alamofire.request(request).responseJSON {...} 

Upvotes: 1

Related Questions