Skip to content

Instantly share code, notes, and snippets.

@foxicode
Created July 29, 2023 13:13
Show Gist options
  • Select an option

  • Save foxicode/cc6c5d6a427a8f917e1fb4899ca7f8ae to your computer and use it in GitHub Desktop.

Select an option

Save foxicode/cc6c5d6a427a8f917e1fb4899ca7f8ae to your computer and use it in GitHub Desktop.
HTML to Attributed String conversion in Swift
public extension String {
var html: NSAttributedString {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(
data: data,
options: [
NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,
NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue
],
documentAttributes: nil
)
} catch {
return NSAttributedString()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment