I have sample URL with following string: https://hello.com/%23/search%3Ftext=%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82
If we decode that, we would get https://hello.com/#/search?text=привет
.
So, we notice that #
, ?
and Cyrillic work gets encoded. The web service does not support encoding #
and ?
, but understands encoded cyrrilic word. It means that I should transform above URL to this: https://hello.com/#/search?text=%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82
How to do that in Swift? Of course, I can simple replace some characters, but it is not maintainable solution because I don't know all characters that can create problem. So, how to solve this? First of all, I can use removePercentEncoding
that returns clean string without any encoding.
"https://hello.com/%23/search%3Ftext=%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82".removePercentEncoding
returns my clean string https://hello.com/#/search?text=привет
. But that one is not convertible to URL
(it just returns nil). So, I should encode it again. I can use "https://hello.com/#/search?text=привет".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
, but it returns https://hello.com/%23/search?text=%D0%BF%D1%80%D0%B8%D0%B2%D0%B5%D1%82
. It is almost what I want, but not exactly. I can replace %23
with #
sign and get desired result but this solution is not maintainable. So, how to solve this problem?