Swift URL appendingPathComponent converts `?` to `%3F`
The generic format of URL is the following:
scheme:[//[userinfo@]host[:port]]path[?query][#fragment]
The thing you have to realize is that the ?
is not part of the path
. It is a separator between path
and query
.
If you try to add ?
to path, it must be URL-encoded because ?
is not a valid character for a path component.
The best solution would be to drop ?
from path
. It has no meaning there. However, if you have a partial URL which you want to append to a base URL, then you should join them as strings:
let url = URL(string: "https://example.com")
let path = "/somePath?"
let urlWithPath = url.flatMap { URL(string: $0.absoluteString + path) }
In short, appendingPathComponent
is not a function that should be used to append URL query.
You should use removingPercentEncoding
on URL's absoluteString
,
let url = URL(string: "https://example.com")
let path = "/somePath?"
let urlWithPath = url?.appendingPathComponent(path).absoluteString.removingPercentEncoding
print(urlWithPath!)