I have two strings encoded differently for spacing:
let first = "https://joytst.page.link/zMx3nAj9DxwcE1JC9?title=New+calendar+test"
let second = "https://joytst.page.link/zMx3nAj9DxwcE1JC9?title=New%20calendar%20test"
let firstOutput = first.removingPercentEncoding //https://joytst.page.link/zMx3nAj9DxwcE1JC9?title=New+calendar+test
let secondOutput = second.removingPercentEncoding //https://joytst.page.link/zMx3nAj9DxwcE1JC9?title=New calendar test
-
Why doesn’t it remove encoding correctly, since + is a correct encoding for space?
-
How can I correctly decode both of them, no matter which one I receive?
2
Answers
If you could decode a whitespace from two different patters, then when you wanted to do the opposite and encode it which one it should take?
That’s the reason why
removingPercentEncoding
only supports one of them.“Why” is a difficult question to answer except for the people who had a hand in implementing
CFURLCreateStringByReplacingPercentEscapes
. The fact is that it doesn’t.I can speculate that it doesn’t because the
+
for space replacement is not part of RFC 3986: Uniform Resource Identifier (URI): Generic Syntax. It should only be used in the query part of the URL, which is of typeapplication/x-www-form-urlencoded
. But this is just my guess.Anyway, if you want to convert
+
to space, you should do so before performing percent-decoding, lest you decode%2b
into+
and then further decode it into a space, leaving no way for your URL to contain a genuine+
after decoding.