Swift 将输入 URL 编码为浏览器显示的最终 URL
Swift encode input URL to be as the final URL the browser shows
在我的 iPhone 上,当我将“zerø.info”粘贴到浏览器 (chrome/firefox) 并进行搜索时,我看到 URL 变成了“zer%c3%” b8.info”然后变成了“xn--zer-2na.info”。
在我的项目(iPhone 应用程序)中,当我调用 urlStr.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
时,我得到“zer%c3%b8.info”。
如何在 Swift 5 中获得最终的 URL "xn--zer-2na.info"?
这叫做“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。
有一个名为 PunycodeSwift 的 CocoaPod 可以生成这些。例如,
"zerø.info".idnaEncoded // xn--zer-2na.info
请注意,此 returns 是可选的,因为如果例如,此转换可能会失败结果超过主机名允许的 63 个字符。
另请注意,并非所有浏览器都支持此功能。
在我的 iPhone 上,当我将“zerø.info”粘贴到浏览器 (chrome/firefox) 并进行搜索时,我看到 URL 变成了“zer%c3%” b8.info”然后变成了“xn--zer-2na.info”。
在我的项目(iPhone 应用程序)中,当我调用 urlStr.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
时,我得到“zer%c3%b8.info”。
如何在 Swift 5 中获得最终的 URL "xn--zer-2na.info"?
这叫做“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。
有一个名为 PunycodeSwift 的 CocoaPod 可以生成这些。例如,
"zerø.info".idnaEncoded // xn--zer-2na.info
请注意,此 returns 是可选的,因为如果例如,此转换可能会失败结果超过主机名允许的 63 个字符。
另请注意,并非所有浏览器都支持此功能。