NSAttributedString来自后台线程中的HTML [英] NSAttributedString from HTML in the background thread
问题描述
我需要的是从相对较大的HTML字符串创建 NSAttributedString
对象,并将它们存储在数据库中(NSAttributedString-s)。当然,我希望在后台线程中这样做。
这是一个简单的代码(它失败了)来演示我正在尝试做什么: p>
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^ {
NSString * HTMLString = @< p> HTML string< / NS<>>;
NSDictionary *选项= @ {NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:@(NSUTF8StringEncoding)};
NSError * error = nil;
NSAttributedString * attributedText = [[NSAttributedString alloc] initWithData:[HTMLString dataUsingEncoding:NSUTF8StringEncoding] options:options documentAttributes:nil error:& error];
});
根据这个讨论根本不可能在后台线程中完成它,因为创建 NSAttributedString
与 NSHTMLTextDocumentType
选项使用 WebKit
,它需要旋转runloop while任何异步工作都会执行。
但是可能有人想通了吗?我有非常简单的HTML,只是文本和链接,可能有一种方法来指定从HTML创建 NSAttributedString
不需要任何 WebKit
-rendering?
或者可能有人可以推荐第三方库来创建 NSAttributedString
WebKit ?
是的,你不能只在主线程中的后台线程。
使用Oliver Drobnik的 NSAttributedString + HTML
class。
代码就像这样 -
NSMutableAttributedString * attrStr = [[NSMutableAttributedString alloc] initWithHTML:< html> dataUsingEncoding:NSUTF8StringEncoding] documentAttributes:nil];
What I need is to create NSAttributedString
objects from relatively big HTML strings and store them (NSAttributedString-s) in the database. And of course I would like to do that in the background thread.
Here is a simple code (which fails) to demonstrate what I'm trying to do:
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];
});
According to this discussion it might not be possible to do it in the background thread at all, since creating NSAttributedString
with NSHTMLTextDocumentType
option uses WebKit
which requires spinning the runloop while any asynchronous work is performed.
But may be someone else figured out the way? I have pretty simple HTMLs, just text and links, may be there is a way to specify that creating a NSAttributedString
from the HTML will not require any "WebKit
-rendering"?
Or may be someone can recommend a third-party lib to create NSAttributedString
s from simple HTMLs that does not use WebKit
?
Yes you can't it in a background thread only on main thread.
Use Oliver Drobnik's NSAttributedString+HTML
class.
Code would be something like this -
NSMutableAttributedString *attrStr = [[NSMutableAttributedString alloc] initWithHTML:<html> dataUsingEncoding:NSUTF8StringEncoding] documentAttributes:nil];
这篇关于NSAttributedString来自后台线程中的HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!