Last active
June 1, 2017 15:26
-
-
Save yanli0303/0825f52eabe8cd0c9230c74f36e60373 to your computer and use it in GitHub Desktop.
Swift: Convert HTML string to NSAttributedString
This file contains 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
// 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