如果url包含中文,如何获取链接swift [复制]

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如果url包含中文,如何获取链接swift [复制]相关的知识,希望对你有一定的参考价值。

这个问题在这里已有答案:

我有一串链接,但它包含中文。 然后我的应用程序将崩溃。 如何防止url是否包含中文,它可以正常显示链接。

var youTextLabel = UILabel()
var message = "https://zh.wikipedia.org/wiki/斯蒂芬·科里"

let linkAttributes = [NSLinkAttributeName: NSURL(string: message)!, //This get error!!
                  NSForegroundColorAttributeName: UIColor.blue,
                  NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue] as [String : Any]

let attributedString = NSMutableAttributedString(string: message)
let urlCharacterCount = message.characters.count
attributedString.setAttributes(linkAttributes, range: NSMakeRange(0, urlCharacterCount))
youTextLabel.attributedText = attributedString

错误信息:

致命错误:在展开Optional值时意外发现nil

答案

您尝试使用的URL需要正确编码。一种解决方案是使用URLComponents构建URL。

var root = "https://zh.wikipedia.org"
var path = "/wiki/斯蒂芬·科里"
var urlcomps = URLComponents(string: root)!
urlcomps.path = path
let url = urlcomps.url!
print(url)

输出:

https://zh.wikipedia.org/wiki/%E6%96%AF%E8%92%82%E8%8A%AC%C2%B7%E7%A7%91%E9%87%8C

另一答案

尝试百分比转义您的网址字符串:

var message = "https://zh.wikipedia.org/wiki/斯蒂芬·科里".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

输出:

“Qazxswpoi”

以上是关于如果url包含中文,如何获取链接swift [复制]的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Swift 中获取两个日期之间的天数? [复制]

如何使用 GoogleAPIClientForREST [Swift] 获取具有共享链接的文件列表

微信公众账号二维码如何提取url链接地址

如何使用 Swift 从 URL 获取 HTML 源代码

Swift 3 - 如何从包含字符串的索引中读取 json 输出

如何使 Http 获取请求 URL 由 swift 3 中的管道组成?