Search code examples
swiftalamofire

Alamofire formatting POST/PUT parameters swift


I have an issue using Alamofire on iOS (swift) :

When I try to send a request (in .POST or .PUT) with parameters like that :

parameters:["description": WhoGives, "images": (
    {
    container = offerImages;
    name = "563f993e4b00ddad7ed42790_0.jpg";
},
    {
    container = offerImages;
    name = "563f993e4b00ddad7ed42790_1.jpg";
}
)]

it results in a httpBody like this :

description="WhoGives"&images[][container]=“offerImages”&images[][name]=“563f993e4b00ddad7ed42790_0.jpg”&images[][container]=“ offerImages”&images[][name]=“563f993e4b00ddad7ed42790_1.jpg"

And I would like it to be :

description="WhoGives"&images[0][container]=“offerImages”&images[0][name]=“563f993e4b00ddad7ed42790_0.jpg”&images[1][container]=“ offerImages”&images[1][name]=“563f993e4b00ddad7ed42790_1.jpg"

As anyone found how to do it? And if so, how?


Solution

  • You will need to use a .Custom parameter encoding to do this. Since there's no RFC spec published around collection URL encoding, Alamofire uses a common convention which works for many servers, but not all.

    Here's a snippet from our ParameterEncoding docs.

    Since there is no published specification for how to encode collection types, the convention of appending [] to the key for array values (foo[]=1&foo[]=2), and appending the key surrounded by square brackets for nested dictionary values (foo[bar]=baz).

    To implement this, you'll want to leverage the logic in the encode method for the .URL case along with the queryComponents method. You'll need to make a slight change to the queryComponents method to put the array index in the parameter value. Then you should be good to go.