🍎

[Swift] UITextView内のハイパーリンク押下でのクラッシュ

2024/06/06に公開

概要

以下のようにURL文字列に日本語があった場合にUITextViewにハイパーリンク化したリンクタップでクラッシュした。
クラッシュログを見てもいまいち詳細な情報を拾えなかったので備忘録として。

例:
https://www.apple.com/jp/テスト

ソースコード

元のURLのままAttributedStringにセットするとリンク属性に適していない場合クラッシュします。
理由はURL内に特定の文字やUnicode文字列を含める場合には、パーセントエンコードが必要であるからということです。

let url = "https://www.apple.com/jp/テスト"
let sampleText = sampleTextView.text
let targetLink = "ハイパーリンク"
let attributedString = NSMutableAttributedString(string: sampleText)
let range = NSString(string: sampleText).range(of: targetLink)
// URLの形式がUITextViewのリンク属性に適していない場合クラッシュするのでエンコード処理が必要
guard let encodeUrl = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) else { return }
attributedString.addAttributes(
  [
     .link: encodeUrl,
     .underlineStyle: NSUnderlineStyle.single.rawValue,
   ],
   range: range
)

参考

https://developer.apple.com/documentation/foundation/url_loading_system

Discussion