3

I'm building an iOS app that takes urls as input. Unicode characters are valid for a tld but when I instantiate a valid URL that contains unicode characters NSURL returns nil. Is this even possible? swift eg. URL(string: "http://➡.ws/䨹")

quin
  • 276
  • 1
  • 9

1 Answers1

2

How to use special characters in URL (Swift 3) :

let myUrl = "http://➡.ws/䨹" as String
let url = URL(string: myUrl) // nil here .. problem !
if let encoded = myUrl.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed){
    let urlencoded = URL(string: encoded) // "http://%E2%9E%A1.ws/%E4%A8%B9" here :) no problem ^^
}
Insou
  • 1,303
  • 1
  • 13
  • 17
  • 2
    This is not correct because you need to encode the host name using Punycode (https://tools.ietf.org/html/rfc3492) instead of the percent encoding. – snak Jul 13 '17 at 14:45
  • When i copy "http://%E2%9E%A1.ws/%E4%A8%B9" and past in Safari, it works. – Insou Jul 13 '17 at 15:00
  • 1
    I'm upvoting as in my case it's working, i don't know it is correct or not. – Abhishek Thapliyal Sep 18 '18 at 07:18
  • FYI: This answer fails on iOS these days and only works in Safari/Mac because Safari itself knows how to encode to punycode. See http://openradar.appspot.com/6923664 for more info. – uliwitness Nov 09 '20 at 10:54
  • 1
    I'm upvoting as well as in my case it's working. In my case I had the host with umlaut and not in puny code format. – Daniel Brolli Jun 16 '21 at 15:00