SwiftHTTP icon indicating copy to clipboard operation
SwiftHTTP copied to clipboard

Parameters not converted properly when using arrays

Open LinusGeffarth opened this issue 7 years ago • 2 comments

First off, thanks for this awesome library!

I want to pass the following dictionary as get parameter:

["param1": 1, "param2": ["a"]]

When passing only non-array values, such as ["param1": 1], it works just fine. But when I pass an array of strings, the parameters are converted to a url as follows:

?param2%5B%5D=a&page=1&param1=1

...manually making this more legible:

?param2[]=a&param1=1

...whereas it obviously should be:

?param2=[a]&param1=1

(note the brackets after param2).

A similar thing happens when trying to code the string array myself by escaping quote chars and then manually adding the parameters in the URL directly:

let urlAppendix = "?param2=[\"\(a)\"]&param1=1"

The response will actually not have any data at all: the URL is nil, the text & data is empty...

Any idea why this is not working properly? Do I need to do anything differently?

LinusGeffarth avatar Jun 11 '18 11:06 LinusGeffarth

@daltoniam, any chance for you to review this?

LinusGeffarth avatar Jun 17 '18 11:06 LinusGeffarth

So, my pull requested (now reverted) actually worked in that particular case, but seemed to make trouble with others. Current workaround would be to convert the array to a string and pass that in a [String: String] dictionary:

extension Array {
    var stringRepresentation: String {
        var str = ""
        self.forEach { str += "\($0)," }
        str = String(str.dropLast()) // drops last comma
        return "[" + str + "]"
    }
}

Then you could do something like:

let strings = ["a", "b", "c"]
let parameters: [String: Any] = [
    "my_array_of_strings": strings.stringRepresentation
]
// will convert to [String: String] = ["my_array_of_strings": "[a,b,c]"]

This works fine.

Note: this only works for GET requests.

LinusGeffarth avatar Jun 25 '18 15:06 LinusGeffarth