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 ?
source share