Skip to content

Instantly share code, notes, and snippets.

@yanli0303
Last active June 1, 2017 15:26
Show Gist options
  • Save yanli0303/0825f52eabe8cd0c9230c74f36e60373 to your computer and use it in GitHub Desktop.
Save yanli0303/0825f52eabe8cd0c9230c74f36e60373 to your computer and use it in GitHub Desktop.
Swift: Convert HTML string to NSAttributedString
// method 1
extension NSAttributedString {
static func from(html: String) throws -> NSAttributedString {
guard let data = html.data(using: String.Encoding.unicode, allowLossyConversion: true) {
throws ArgumentError.invalidArgument("Invalid `html` string, failed to convert it to `Data`.")
}
return try NSAttributedString(
data: data,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil
)
}
}
// method 2
extension NSAttributedString {
static func from(html: String) -> NSAttributedString? {
guard let data = html.data(using: String.Encoding.utf8, allowLossyConversion: true) {
return nil
}
return NSAttributedString(html: data, options: [:], documentAttributes: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment