Created
May 27, 2019 11:10
-
-
Save yusuke024/8af43eefa694a800074df2a04ed7cbc9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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