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

问题描述 投票:0回答:2

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

我有一串链接,但它包含中文。 然后我的应用程序将崩溃。 如何防止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

ios swift string hyperlink attributes
2个回答
3
投票

您尝试使用的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


3
投票

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

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

输出:

“Qazxswpoi”

© www.soinside.com 2019 - 2024. All rights reserved.