Skip to content

Instantly share code, notes, and snippets.

@yusuke024
Created May 27, 2019 11:10
Show Gist options
  • Save yusuke024/8af43eefa694a800074df2a04ed7cbc9 to your computer and use it in GitHub Desktop.
Save yusuke024/8af43eefa694a800074df2a04ed7cbc9 to your computer and use it in GitHub Desktop.
extension NSAttributedString {
convenience init?(htmlString: String) {
guard let data = htmlString.data(using: .unicode) else { return nil }
let options: [NSMutableAttributedString.DocumentReadingOptionKey: Any] = [.documentType: NSAttributedString.DocumentType.html]
do {
try self.init(data: data, options: options, documentAttributes: nil)
} catch {
return nil
}
}
func attributedString(byKeepingAttribute shouldKeepAttribute: ((NSAttributedString.Key, Any, NSRange) -> Bool)) -> NSAttributedString {
let mas = NSMutableAttributedString(string: string)
enumerateAttributes(in: NSRange(location: 0, length: length), options: []) { attributes, range, _ in
for (key, value) in attributes {
if shouldKeepAttribute(key, value, range) {
mas.addAttribute(key, value: value, range: range)
}
}
}
return NSAttributedString(attributedString: mas)
}
}
let text = #"Hello, <a href="http://www.example.com">World</a>.<br />こんにちは、<a href="http://www.example.com">世界</a>。"#
let at = NSAttributedString(htmlString: text)?.attributedString { k, _, _ in k == .link }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment