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

标签 ios swift string hyperlink attributes

<分区>

我有一串链接,但是里面有中文。
然后我的应用就会崩溃。
如何防止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

错误信息:

fatal error: unexpectedly found nil while unwrapping an Optional value

最佳答案

尝试对您的 url 字符串进行百分比转义:

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

输出:

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

关于ios - 如果url包含中文,如何通过swift获取链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48088342/

相关文章:

ios - 表有很多列ios swift

ios - 播放嵌入式YouTube视频iOS 9时出错

ios - 在 iOS sdk 中初始化 View Controller

swift - 在 SwiftUI 的 ForEach 中获取索引

string - "set foo to text returned of"代表数字吗?

java - 不使用 Java Matcher 和 Pattern API 删除特殊字符

ios - 在完成之前停止 animateWithDuration

ios - 苹果可以在我的应用程序中批准信用卡表格吗?

ios - Xcode 6.1 'Swift REPL built into the Xcode debugger can inspect and manipulate your running app' 不工作

Swift 将字符串转换为函数名 (#selector)