This is how I add a query params to a base URL:
let baseURL: URL = ...
let queryParams: [AnyHashable: Any] = ...
var components = URLComponents(url: baseURL, resolvingAgainstBaseURL: false)
components?.queryItems = queryParams.map { URLQueryItem(name: $0, value: "\($1)") }
let finalURL = components?.url
The problem emerges when one of values contains a +
symbol. For some reason it's not encoded to %2B
in the final URL, instead it stays +
. If I do encoding myself and pass %2B
, NSURL
encodes %
and the 'plus' becomes %252B
.
The question is how can I have %2B
in the instance of NSURL
?
P.S. I know, I wouldn't even have this problem if I constructed a query string myself and then simply pass a result to the NSURL
's constructor init?(string:)
.
As pointed out in the other answers, the "+" character is valid in a query string, this is also stated in the
queryItems
documentation.On the other hand, the W3C recommendations for URI addressing state that
This can be achieved by "manually" building the percent encoded query string, using a custom character set:
Another option is to "post-encode" the plus character in the generated percent-encoded query string:
Can you try using
addingPercentEncoding(withAllowedCharacters: .alphanumerics)
?I just put together a quick playground demonstrating how this works:
URLComponents is behaving correctly: the
+
is not being percent-encoded because it is legal as it stands. You can force the+
to be percent-encoded by using.alphanumerics
, as explained already by Forest Kunecke (I got the same result independently but he was well ahead of me in submitting his answer!).Just a couple of refinements. The OP's
value: "\($1)"
is unnecessary if this is a string; you can just sayvalue:$1
. And, it would be better to form the URL from all its components.This, therefore, is essentially the same solution as Forest Kunecke, but I think it is more canonical and it is certainly more compact ultimately:
EDIT Rather better, perhaps, after suggested correction from Martin R: we form the entire query and percent-encode the pieces ourselves, and tell the URLComponents that we have done so: