2017-01-31 167 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)) 
    } 
} 
}