Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSAttributedString from HTML in the background thread

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 NSAttributedStrings from simple HTMLs that does not use WebKit?

like image 913
dariaa Avatar asked Feb 04 '14 17:02

dariaa


2 Answers

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

like image 169
user3762956 Avatar answered Sep 28 '22 05:09

user3762956


You can try NSAttributedString+DDHTML. AFAIK it doesn't depend on WebKit and I used it successfully for simple HTMLs. I haven't tried using it in the background thread, but I suppose it shouldn't be a problem.

And watch out - it may crash when HTML includes font which is unavailable on iOS. I've issued a pull request for that.

like image 33
Michał Ciuba Avatar answered Sep 28 '22 06:09

Michał Ciuba