read
This is a common pitfall, because of an Apple bug, since forever.
If you want to encode a URL as a query item (eg. the value is a callback URL like “http://example.com/?x=1&y=2”), it won’t work correctly using addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
.
The “=” and “&” won’t be escaped, and that is problematic.
There are solutions using a stricter character set, by removing other characters (so that those characters will be escaped):
var stricterSet = NSCharacterSet.urlQueryAllowed
stricterSet.remove(charactersIn: ";/?:@&=+$, ")
url.addingPercentEncoding(withAllowedCharacters: stricterSet)
Alternatively, use URLComponent
Another way is to use URLComponent
and URLQueryItem
.
var components = URLComponents(..)
components?.queryItems = [
.init(name: "callback", value: url) // Will escape =&
]
print(components?.url)
Let them handle the encoding for the query items.
Compared to the stricterSet
above, query item will only encode =, & and space. Not as strict, but seems good enough.