我需要的是从相对较大的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渲染”?
或者可能有人可以推荐第三方库从不使用WebKit的简单HTML创建NSAttributedStrings?
解决方法
是的,你不能只在主线程的后台线程中.
使用Oliver Drobnik的NSAttributedString HTML类.
使用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
原文地址:https://www.jb51.cc/html/231583.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。