我需要的是从相对较大的 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];
关于html - 后台线程中来自 HTML 的 NSAttributedString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21559011/