Last Updated: February 25, 2016
·
16.02K
· anthonylevings

Creating an NSAttributedString from HTML (or RTF) in iOS 7

Following additions to the iOS 7 NSAttributedString class it is now possible to create attributed strings using HTML.

For example:

// Create an NSURL pointing to the HTML file
NSURL *htmlString = [[NSBundle mainBundle]
                         URLForResource: @"helloworld" withExtension:@"html"];

// Transform HTML into an attributed string   
NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc]   initWithFileURL:htmlString options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];

// Instantiate UITextView object
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(20,20,self.view.frame.size.width,self.view.frame.size.height)];

// Add attributed string to text view   
textView.attributedText=stringWithHTMLAttributes;

// Add the text view to the view hierarchy
[self.view addSubview:textView];

Two things to note here: (1) this is a rough and ready use of UITextView - see this earlier blogpost for a better implementation (2) you'll need to save an accompanying file called 'helloworld.html' for this to work.

Here is the helloworld.html file:

<html><p>Hello <i>World</i></p></html>

As well as HTML you can use RTF and RTFD files to create attributed strings, using NSRTFTextDocumentType and NSRTFDTextDocumentType respectively in place of NSHTMLTextDocumentType.

Finally, you must take account of the following notes from Apple: "Calling [this method] from the main thread works (but can still time out if the HTML contains references to external resources, which should be avoided at all costs). The HTML import mechanism is meant for implementing something like markdown (that is, text styles, colors, and so on), not for general HTML import."

This warning from Apple does not mean, however, that you can't use CSS, in fact you can transform HTML files with linked CSS files into NSAttributedStrings, opening the door to replacing the use of UIWebView in eBook apps with the use of UITextViews.

2 Responses
Add your response

How can i convert from attributed string back to HTML?

over 1 year ago ·