如果url包含中文,如何通过swift获取链接

tol*_*Thx 1 string attributes hyperlink ios 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
Run Code Online (Sandbox Code Playgroud)

错误信息:

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

Tj3*_*j3n 6

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

var message = "https://zh.wikipedia.org/wiki/???·??".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
Run Code Online (Sandbox Code Playgroud)

输出:

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