html - 后台线程中来自 HTML 的 NSAttributedString

标签 html ios ios7 nsattributedstring

我需要的是从相对较大的 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];
});

根据 this discussion可能根本不可能在后台线程中执行此操作,因为使用 NSHTMLTextDocumentType 选项创建 NSAttributedString 使用 WebKit 需要旋转运行循环,同时执行任何异步工作。

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

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

最佳答案

是的,您不能仅在主线程的后台线程中使用它。 使用 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

关于html - 后台线程中来自 HTML 的 NSAttributedString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21559011/

相关文章:

javascript - 尝试使用 javascript 连接 Access 数据库

ios - 过渡到 iOS 7 : correct viewport setting for jQuery/iPhone Webapps viewed on iPads

ios - 触摸背景时,如何防止 UIActionSheet 被关闭?

ios - 在后台任务中安排通知

php - html php通过多个页面和内部表单传递变量

javascript - 当最大高度减小时,最大高度过渡不起作用

php - 如何使用数据库中的数据和for循环生成表(php)

ios - 如果 Collection View 嵌入在 ios 中的 TableView 中,如何始终显示 Collection View 的第一项

ios - 带有 c/c++ 模块错误的 Android Studio KMM 项目

iOS8 照片框架 : How to get the name(or filename) of a PHAsset?