2017-01-31 120 views
3

我使用这种方式,它工作正常,但有一个缓慢回落,因为NSHTMLTextDocumentType的使用为我做了我的研究显示HTML内容有效

do { 

    let attributedOptions:[String: Any] = [ 
     NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, 
     NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue] 

    let date = html.data(using: String.Encoding.utf8, allowLossyConversion: true)! 

    return try NSAttributedString(data: data, options: attributedOptions , documentAttributes: nil) 

} catch let error as NSError { 

    print("htmo2String \(error)") 
} 

任何想法如何做到这一点的速度更快或另一种有效的方式来做到这一点!

回答

2

也许你可以在执行队列中的解析代码...

func parse(_ html: String, completionHandler: @escaping (_ attributedText: NSAttributedString?) -> (Void)) -> Void 
{ 
    let htmlData = text.data(using: String.Encoding.utf8, allowLossyConversion: false) 

    let options: [String: AnyObject] = [ 
     NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType as AnyObject 
    ] 

    completionHandler(try? NSAttributedString(data: htmlData!, options: options, documentAttributes: nil)) 
} 

现在调用函数和响应等待...

let queue: DispatchQueue = DispatchQueue(label: "com.yourcompany.Process./html_converter") 

queue.async 
{ 
    parse("<p>¡Hola mundo</p>", completionHandler: { (attributtedString: NSAttributedString?) -> (Void) in 
     if let attributtedString = attributtedString 
     { 
      DispatchQueue.main.async 
      { 
       print("str:: \(attributtedString)") 
      } 
     } 
    }) 
} 
+0

或缓存它:将它与您的异步解析保存到HTML来自对象 – muescha

+0

做它在队列上的异步似乎是一个好主意 –

0

您是否尝试使用UIWebView呈现HTML内容?

您可以根据需要显示来自字符串或URL的HTML。

这里是从字符串显示HTML的例子:

string sHTMLContent = "<html><head><body><p>Hello World</p></body></head></html>"; 
m_WebView.LoadHtmlString(sHTMLContent , null); 

然后你可以设置网页视图的大小等于与约束你的TextView。如果需要,webview将自动滚动。

+0

你更好地理解这个问题,他问的是有效的方法。 – karthikeyan

0

最终的字符串扩展显示html字符串有效地与@Adolfo异步想法

能够更改字体和颜色^ _^

extension String { 

func html2StringAsync(_ fontSize: CGFloat? = nil, color: UIColor? = nil, completionBlock:@escaping (NSAttributedString) ->()) { 

    let fontSize = fontSize ?? 10 

    let fontColor = color ?? UIColor.black 

    let font = "Avenir !important" 

    let html = "<div style=\"font-family:\(font); font-size:\(fontSize)pt; color:\(fontColor.hexString);\">" + self + "</div>" 

    if let data = html.data(using: String.Encoding.utf8, allowLossyConversion: true){ 

     DispatchQueue.main.async { 

      do { 

       let attributedOptions:[String: Any] = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, 
                 NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue] 

       let attrStr = try NSAttributedString(data: data, options: attributedOptions , documentAttributes: nil) 

       completionBlock(attrStr) 

      } catch let error as NSError { 

       print("htmo2String \(error)") 
      } 
     } 
    }else{ 

     completionBlock(NSAttributedString(string: self)) 
    } 
} 
}