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
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…