在后台线程从HTML的NSAttributedString

我需要的是从相对较大的HTMLstring创buildNSAttributedString对象,并将它们(NSAttributedString-s)存储在数据库中。 当然,我想在后台线程中这样做。

这里是一个简单的代码(失败)来演示我正在尝试做什么:

 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]; }); 

根据这个讨论 ,根本不可能在后台线程中执行它,因为使用NSHTMLTextDocumentType选项创buildNSHTMLTextDocumentType选项使用WebKit ,它需要在执行任何asynchronous工作时旋转runloop。

但可能是别人想通了? 我有非常简单的HTML,只是文本和链接,可能有一种方法来指定,从HTML创build一个NSAttributedString不会需要任何“ WebKit -rendering”?

或者可能有人可以推荐第三方库从简单的HTML不使用WebKit创buildNSAttributedString

是的,你不能只在主线程后台线程。 使用Oliver Drobnik的NSAttributedString+HTML类。

代码会是这样的 –

 NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithHTML:<html> dataUsingEncoding:NSUTF8StringEncoding] documentAttributes:nil]; 

链接 – https://github.com/InfiniteLoopDK/NSAttributedString-Additions-for-HTML/blob/master/Classes/NSAttributedString%2BHTML.m

你可以试试NSAttributedString + DDHTML 。 AFAIK它不依赖于WebKit,我成功地使用它简单的HTML。 我没有尝试在后台线程中使用它,但我想这不应该是一个问题。

注意 – 当HTML包含iOS上不可用的字体时,可能会崩溃。 我已经发出拉请求 。