Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Parameters not converted properly when using arrays #293

Open
LinusGeffarth opened this issue Jun 11, 2018 · 2 comments
Open

Parameters not converted properly when using arrays #293

LinusGeffarth opened this issue Jun 11, 2018 · 2 comments

Comments

@LinusGeffarth
Copy link

LinusGeffarth commented Jun 11, 2018

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
Copy link
Author

@daltoniam, any chance for you to review this?

LinusGeffarth added a commit to LinusGeffarth/SwiftHTTP that referenced this issue Jun 25, 2018
Arrays now properly converted to string such as "['1', '2']" and passed to request as parameter.
Fixes daltoniam#293.
@LinusGeffarth LinusGeffarth reopened this Jun 25, 2018
@LinusGeffarth
Copy link
Author

LinusGeffarth commented Jun 25, 2018

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant