0

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?

neo
  • 1,314
  • 2
  • 14
  • 34
  • 1
    Important: the accepted answer from the link is _not_ how you should compose a URL! Instead, use [URLComponents](https://developer.apple.com/documentation/foundation/urlcomponents). There is also a correct answer in this question: https://stackoverflow.com/a/43668198/465677. Also, there are literally hundreds of these kind of questions. All issues can be solved with URLComponents, provided client _and_ server obeying the rules stated in the related [RFC](https://datatracker.ietf.org/doc/html/rfc3986). – CouchDeveloper Sep 29 '21 at 09:01
  • @CouchDeveloper # sign is still encoded in url even after using URLComponents. How to avoid that? – neo Sep 29 '21 at 09:47
  • Using URLComponents to _compose_ your URL out from the given parts. If you not have noticed, your given URL string is likely not what you want to have: scheme: https, host: "hello.com", path: "/#/search?text=привет", query: nil, fragment: nil – CouchDeveloper Sep 29 '21 at 09:57

0 Answers0