Convert HTML to NSAttributedString and vice versa

suggest change

HTML 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];

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents