When working with URLs as strings, you should encode them to be valid as a URL; One of the most popular examples of encoding the URL is that the " " (space) would be encoded as "%20".
So in your case the encoded value of your url should be:
www.mydomain.com%2Fkey=%E0%A4%85%E0%A4%95%E0%A5%8D%E0%A4%B7%E0%A4%AF
As you noticed the value of the key
is changed
from: "अक्षय"
to:"%E0%A4%85%E0%A4%95%E0%A5%8D%E0%A4%B7%E0%A4%AF"
which will let the URL to be valid.
How to:
you could get the above result like this:
let string = "www.mydomain.com/key=अक्षय"
if let encodedString = string.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed), let url = URL(string: encodedString) {
print(url) // www.mydomain.com%2Fkey=%E0%A4%85%E0%A4%95%E0%A5%8D%E0%A4%B7%E0%A4%AF
}
Note that there is optional binding for both the encoded string and the url for the purpose of being safe.
Decoding the URL:
You could also returns to the original unencoded url (decoding it) like this:
let decodedString = "www.mydomain.com%2Fkey=%E0%A4%85%E0%A4%95%E0%A5%8D%E0%A4%B7%E0%A4%AF"
if let unwrappedDecodedString = decodedString.removingPercentEncoding {
print(unwrappedDecodedString) // www.mydomain.com/key=अक्षय
}
Again, optional binding to be safe.