0

I'm using URLQueryItem to encode query values but when I pass queries to the URLComponent in the url property query keys are encoded too.

var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false)
urlComponents.queryItems = [URLQueryItem]()
for (key,value) in parameters {
    let queryItem = URLQueryItem(name: key,
                                 value: "\(value)".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed))
    urlComponents.queryItems?.append(queryItem)
}
print("URLComponents Query Items:\n \(urlComponents.queryItems)")
print("URLComponents URL:\n \(urlComponents.url)")

Output is:

URLComponents Query Items:
 Optional([per_page=10, filters[status]=Active])
URLComponents URL:
 Optional(https://example.com/endpoint?per_page=10&filters%5Bstatus%5D=Active)

How can this be prevented? I don't want query names be encoded.

Maysam
  • 6,738
  • 13
  • 63
  • 94

1 Answers1

0

Remove the explict .addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) call - URLQueryItem takes care of the encoding.

Gereon
  • 14,827
  • 4
  • 36
  • 62
  • It didn't help. Encoding was done on value by the way. – Maysam May 29 '20 at 20:09
  • Oops, sorry, misread that part. AFAIK there's no way you can tell `URLQueryItem` not to percent-encode `[` and `]`, but it also does no harm except maybe visually – Gereon May 29 '20 at 20:18
  • Thanks, in my case, the server cannot read the key if encoded. – Maysam May 29 '20 at 20:19
  • You should give your server folks a stern talking-to, they're violating RFC 3986. – Gereon May 29 '20 at 20:25
  • @LeoDabus sorry? it supposed to be `filters[somethng]` – Maysam May 29 '20 at 20:51
  • @Maysam Even if you use the regular `URL(string:)` initializer it does result in `"https://example.com/endpoint?per_page=10&filters%5Bstatus%5D=Active\n"`. I might be wrong but I don't think you can avoid it. – Leo Dabus May 29 '20 at 21:08
  • Yes, it seems there is no way to avoid it. – Maysam May 29 '20 at 21:12
  • https://www.dropbox.com/s/0g9sokq9wwlev9o/URL%5Bpercent%5Dencoding.jpg?dl=1 – Leo Dabus May 29 '20 at 21:14
  • 1
    I have added the same characters to the dropbox file name as you can see above. Same result. You will need to fix the backend – Leo Dabus May 29 '20 at 21:15