Glenn Glenn -4 years ago 71
iOS Question

Alamofire Passing Parameter With Common Keys and Multiple Values?

I need to do this in my project:

I can do this easily if I manually append strings to my URL in Alamofire, but I don't want that. I want the parameters as Parameter object.

multiple values in one common key for parameter

enter image description here

What I've been doing:

public func findCreate(tags: [String], withBlock completion: @escaping FindCreateServiceCallBack) {

/*[]=fff&category_name[]=sss */

let findCreateEndpoint = CoreService.Endpoint.FindMultipleCategories

let parameters: Parameters = ["category_name[]" : tags]

method: .post,
parameters: parameters,
encoding: URLEncoding(destination: .queryString),
headers: nil
).responseJSON { (response) in

The current result if I run this are okay but the values sent to the server has [" "]. For example:


Again, the questions are, in which part of my whole codes I'm wrong? How can I send parameters like above that has one common key and multiple values?

I also have tried adding encoding option to the Alamofire.request() If I add
encoding: JSONEncoding.prettyPrinted
encoding: JSONEncoding.default
I get status code 500.

Some links that have the same question but no exact answers, I always see posts that have answers like use a custom encoding and that's it.

Additional info:

This works, but I need to send multiple String:

let parameters: [String : Any] = ["category_name[]" : tags.first!]

And this works as well:

Alamofire.request("[]=fff&category_name[]=sss", method: .post).responseJSON { (data) in

Answer Source

You don't need a custom encoding for this format.

You can send parameters encoded like this:


By using URLEncoding (which you're already doing) and including the multiple values that should have the same key in an array:

let parameters: Parameters = ["category_name": ["rock", "paper"]]

It'll add the [] after category_name for you, so don't include it when you declare the parameters.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download