NSAttributedString from HTML in the background thread

html, ios, ios7, nsattributedstring

Solution

Yes you can't it in a background thread only on main thread. Use Oliver Drobnik's `NSAttributedString+HTML` class.

Code would be something like this -

NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithHTML:<html> dataUsingEncoding:NSUTF8StringEncoding] documentAttributes:nil];

Link - https://github.com/InfiniteLoopDK/NSAttributedString-Additions-for-HTML/blob/master/Classes/NSAttributedString%2BHTML.m

Problem

What I need is to create `NSAttributedString` objects from relatively big HTML strings and store them (NSAttributedString-s) in the database. And of course I would like to do that in the background thread. Here is a simple code (which fails) to demonstrate what I'm trying to do: ``` dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ NSString *HTMLString = @"<p>HTML string</p>"; NSDictionary *options = @{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute : @(NSUTF8StringEncoding)}; NSError *error = nil; NSAttributedString *attributedText = [[NSAttributedString alloc] initWithData:[HTMLString dataUsingEncoding:NSUTF8StringEncoding] options:options documentAttributes:nil error:&error]; }); ``` According to this discussion it might not be possible to do it in the background thread at all, since creating `NSAttributedString` with `NSHTMLTextDocumentType` option uses `WebKit` which requires spinning the runloop while any asynchronous work is performed. But may be someone else figured out the way? I have pretty simple HTMLs, just text and links, may be there is a way to specify that creating a `NSAttributedString` from the HTML will not require any "`WebKit`-rendering"? Or may be someone can recommend a third-party lib to create `NSAttributedString`s from simple HTMLs that does not use `WebKit`?

Original source