我没有找到任何减少转换时间的方法。但是有一种方法可以“黑客”加载时间。
似乎第一次调用转换过程需要很长时间,但在下一次调用时需要的时间较少。通过这种方式,我解决了在我的AppDelegate中加载一小段“html垃圾邮件”的问题。因此,在使用应用程序期间,用户将不会注意到缓慢的加载。
AppDelegate:
override func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
super.application(application, willFinishLaunchingWithOptions: launchOptions)
try! NSMutableAttributedString(
data: "<a>asdasd</a>".data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [
NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.unicode.rawValue
],
documentAttributes: nil)
return true
}
在 ViewControllers 中,您可以像平常一样调用:
var html = "<b>Whatever...</b>"
var attributedText = try! NSMutableAttributedString(
data: html.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
HTML 导入器不应该从后台线程调用(也就是说,选项字典包括 NSDocumentTypeDocumentAttribute 并且其值为 NSHTMLTextDocumentType)。
- Larme