Swift encode input URL to be as the final URL the browser shows

Viewed 79

On my iPhone, when I paste "zerø.info" into a browser (chrome/firefox) and search, then I see the URL turn to "zer%c3%b8.info" and then it's turned into "xn--zer-2na.info". In my project (iPhone app), when I call urlStr.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) I get "zer%c3%b8.info". How can I get the final URL "xn--zer-2na.info" in Swift 5?

1 Answers

This is called "IDNA encoding", which is basically the Punycode of the domain name prefixed with "xn--". There is no built-in way of generating this in Swift, according to this forum post.

There is a CocoaPod called PunycodeSwift that generates these. For example,

"zerø.info".idnaEncoded // xn--zer-2na.info

Note that this returns an optional, since this conversion can fail if e.g. the result is longer than the allowed 63 characters of a host name.

Also note that not all browsers support this.

Related