【发布时间】:2020-03-30 19:54:49
【问题描述】:
我需要的是从相对较大的 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,这需要在执行任何异步工作时旋转runloop。
但是可能是其他人想出了办法吗?我有非常简单的 HTML,只有文本和链接,可能有一种方法可以指定从 HTML 创建 NSAttributedString 不需要任何“WebKit-rendering”?
或者可能有人可以推荐一个第三方库来从不使用WebKit的简单HTML创建NSAttributedStrings?
【问题讨论】:
标签: html ios ios7 nsattributedstring