Joshua Joshua - 6 months ago 171
Objective-C Question

Convert HTML to NSAttributedString in iOS

I am using a instance of

UIWebView
to process some text and color it correctly, it gives the result as HTML but rather than displaying it in the
UIWebView
I want to display it using
Core Text
with a
NSAttributedString
.

I am able to create and draw the
NSAttributedString
but I am unsure how I can convert and map the HTML into the attributed string.

I understand that under Mac OS X
NSAttributedString
has a
initWithHTML:
method but this was a Mac only addition and is not available for iOS.

I also know that there is a similar question to this but it had no answers, I though I would try again and see whether anyone has created a way to do this and if so, if they could share it.

pix pix
Answer

In iOS 7, UIKit added an initWithData:options:documentAttributes:error: method which can initialize an NSAtttributedString using HTML, eg:

[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding] 
                                 options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                                           NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)} 
                      documentAttributes:nil error:nil];