Tag Archives: nsattributedstring

How To Convert HTML to NSAttributedString

I’m not sure what the best practice is these days when displaying HTML content in your app. It seems you can either put it into a UIWebView or you can, as of iOS 7, convert it to an NSAttributedString and put it into a UILabel, UITextField, etc. I have been leaning toward the latter recently and thought I’d post the 2 lines of code required to make that happen.

NSAttributedString *stringWithHTMLAttributes = [[NSAttributedString alloc] initWithData:[self.htmlText dataUsingEncoding:NSUTF8StringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding)} documentAttributes:nil error:nil];

self.htmlLabel.attributedText = stringWithHTMLAttributes;

The above code assumes you have HTML stored in an NSString variable called “self.htmlText” and a UILabel called htmlLabel and that your encoding is UTF8.

Let me know if you have any questions or if there is a better practice I’m not aware of.