Create NSAttributedString from HTML in iOS 7

With the release of iOS 7, Apple introduced the method below in the NSAttributedString UIKit Additions:

initWithFileURL:options:documentAttributes:error:

With this little gem you can create an NSAttributedString from data retrieved via URL, and using a document attribute of NSDocumentTypeDocumentAttribute, generate the string from HTML.

Let’s look at an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Create URL from HTML file in application bundle
NSURL *html = [[NSBundle mainBundle] URLForResource: @"test" withExtension:@"html"];
 
// Create attributed string from HTML
NSAttributedString *attrStr = [[NSAttributedString alloc]
  initWithFileURL:html
  options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType}
  documentAttributes:nil error:nil];
 
// Create textview, add attributed str
UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(10, 10, 320, 50)];
[textView setAttributedText:attrStr];
 
// Show textview
[[self view] addSubview:textView];

The primary code of interest is line 7 – an NSDictionary is populated with a key-value pair where the key (NSDocumentTypeDocumentAttribute) specifies the value will identify the document type, in our case, HTML.

For my example, I used the following HTML contents, stored in a file with the name test.html

<div style="background-color:#F1F1F1; font-size:14px; color:#304182; 
  text-align:center; margin-left:10px; padding-right:10px"> 
<p>iOS <span style="font-size:18px; color:#E88834;">Developer</span> Tips</p>
</div>

Here’s the output:

NSAttributedString from HTML