swiftpostparametersurlrequest

Swfit URLRequest POST How to make a request with duplicated parameter keys


I'm currently working on a project which uses Inoreader APIs, and there is one required post request with duplicated parameter keys.

https://www.inoreader.com/reader/api/0/edit-tag?a=user/-/state/com.google/read&i=12345678&i=12345679

As you can see duplicated i parameters. I've tried below to set httpBody of URLRequest, failed silently.

var parameters = [String: Any]()
parameters["i"] = idArray
parameters["a"] = "user/-/state/com.google/read"
let jsonData = try JSONSerialization.data(withJSONObject: parameters, options: [])
request.httpBody = jsonData
// I omitted other codes for simplicity

Then I've tried to chain every element of idArray with "&i=", assigned it to parameters["i"], also failed silently.

// chainedID was something like 123&i=456&i=789, to make it looks like as url example given by documentation
parameters["i"] = chainedID

How can I do that? This API is working perfectly with one item, but I can't get it work on multiple items. It claims will work with multiple items.


Solution

  • Based on the example that you posted and the ones that the documentation mentions, although the request is POST can accept parameters in the URL's query.

    So, the solution would be to compose your request using URLComponents:

    var components = URLComponents(string: "https://www.inoreader.com/reader/api/0/edit-tag")
    var queryItems = [
        URLQueryItem(name: "a", value: "user/-/state/com.google/read")
    ]
    idArray.forEach {
        queryItems.append(URLQueryItem(name: "i", value: $0))
    }
    components?.queryItems = queryItems
    guard let url = components?.url else { return }
    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    

    and not use JSON parameters in the request's body.