daltoniam / SwiftHTTP

Thin wrapper around NSURLSession in swift. Simplifies HTTP requests.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Parameters not converted properly when using arrays

LinusGeffarth opened this issue · comments

commented

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?

commented

@daltoniam, any chance for you to review this?

commented

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.