Convert HTML to NSAttributedString and vice versa
suggest changeHTML to NSAttributedString:
// HTML String
NSString *htmlString = @"<!DOCTYPE html><html><body><h1>My First Heading</h1><p>My first paragraph.</p></body></html>";
// Convert the HTML string to an NSAttributedString. Passing nil for error ignores conversion failures.
NSAttributedString *attributedString = [[NSAttributedString alloc]
initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding) }
documentAttributes:nil
error:nil];
NSAttributedString to HTML:
// Attributes that describe the exported document
NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
// Save the attributed string as HTML data
NSData *htmlData = [attributedString dataFromRange:NSMakeRange(0, attributedString.length) documentAttributes:documentAttributes error:NULL];
// Convert that data to an HTML string with UTF-8 encoding
NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents