繁体   English   中英

后台线程中来自 HTML 的 NSAttributedString

[英]NSAttributedString from HTML in the background thread

我需要的是从相对较大的 HTML 字符串创建NSAttributedString对象并将它们(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选项创建NSAttributedString使用WebKit ,这需要在执行任何异步工作时旋转 runloop。

但也许其他人想出了办法? 我有非常简单的 HTML,只有文本和链接,可能有一种方法可以指定从 HTML 创建NSAttributedString不需要任何“ WebKit -rendering”?

或者可能有人可以推荐第三方库来NSAttributedString使用WebKit简单 HTML 创建NSAttributedString s?

是的,您不能仅在主线程上的后台线程中使用它。 使用 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 上不可用的字体时,它可能会崩溃。 我已经为此发出了拉取请求

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM