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
?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With