简体   繁体   中英

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.

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)

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 {...} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM