Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

ios - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...