NSAttributedString from HTML in a background thread

I need to create NSAttributedString objects from relatively large HTML strings and store them (NSAttributedString-s) in the database. And of course, I would like to do this 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 may not be possible to do this in the background thread at all, since creating an NSAttributedString using the NSHTMLTextDocumentType option uses WebKit , which requires the runloop to rotate when performing any asynchronous operation.

But maybe someone else understood the way? I have fairly simple HTML, just text and links, maybe there is a way to indicate that no โ€œ WebKit bindingโ€ is required to create an NSAttributedString from HTML?

Or maybe someone can recommend a third-party lib to create an NSAttributedString from simple HTML files that don't use WebKit ?

+4
source share
2 answers

Yes, you cannot in the background thread only in the main thread. Use the Oliver Drobnik class NSAttributedString+HTML .

The 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

+3
source

You can try NSAttributedString + DDHTML . AFAIK is not dependent on WebKit, and I have successfully used it for simple HTML. I have not tried using it in the background thread, but I suppose this is not a problem.

And note that this may crash when the HTML contains a font that is not available on iOS. I posted a migration request for this.

+1
source

Source: https://habr.com/ru/post/1257667/


All Articles