How do i convert NSAttributedString into HTML string?
Solution 1:
Use dataFromRange:documentAttributes:
with the document type attribute (NSDocumentTypeDocumentAttribute
) set to HTML (NSHTMLTextDocumentType
):
NSAttributedString *s = ...;
NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSData *htmlData = [s dataFromRange:NSMakeRange(0, s.length) documentAttributes:documentAttributes error:NULL];
NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
Solution 2:
This is a swift 4 conversion of @omz answer, hope is useful to anyone landing here
extension NSAttributedString {
var attributedString2Html: String? {
do {
let htmlData = try self.data(from: NSRange(location: 0, length: self.length), documentAttributes:[.documentType: NSAttributedString.DocumentType.html]);
return String.init(data: htmlData, encoding: String.Encoding.utf8)
} catch {
print("error:", error)
return nil
}
}
}