1

I have a string of link, but it contains the Chinese.
And then my app will crash.
How to prevent whether url contains Chinese or not, it can show the link normally .

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

error message:

fatal error: unexpectedly found nil while unwrapping an Optional value

tolerate_Me_Thx
  • 387
  • 2
  • 7
  • 21

2 Answers2

8

Try percent escape your url string:

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

Output:

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

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Tj3n
  • 9,837
  • 2
  • 24
  • 35
3

The URL you are trying to use needs to be properly encoded. One solution is to build the URL using URLComponents.

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

Output:

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

rmaddy
  • 314,917
  • 42
  • 532
  • 579