2015-08-13 14 views
12

Ho una stringa contenente HTML. Mi piacerebbe visualizzare l'HTML in un controllo TextView. Ho trovato un po 'di codice e l'ho provato:Come visualizzare testo HTML in TextView

def = "some html text" 

definition.attributedText = NSAttributedString(
    data: def.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!, 
    options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], 
     documentAttributes: nil, 
     error: nil) 

Sulla possibilità ottengo un errore:

[String: String] is not convertible to string.

Qualcuno può aiutarmi visualizzo HTML in un TextView?

+0

Sembra NSAttributedString restituisce un array bidimensionale. Penso che dovrai ripetere l'enumerazione. – ouflak

risposta

39

Questo funziona per me. Ricordate che il costruttore NSAttributedString ora throws un oggetto NSError:

Swift 3:

do { 
    let str = try NSAttributedString(data: def.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil) 
} catch { 
    print(error) 
} 

Swift 2.x:

do { 
    let str = try NSAttributedString(data: def.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil) 
} catch { 
    print(error) 
} 
+0

Quando uso questo codice, ottengo il seguente messaggio nella console: "+ [CATransaction synchronize] chiamato all'interno della transazione." Sai come aggiustarlo? –

+0

@EvanKaminsky Hmm, non sono sicuro senza più contesto. Puoi fare una nuova domanda che mostra dove stai chiamando questo e cos'è la stringa HTML? – JAL

+0

Credo che sia lo stesso problema di http://stackoverflow.com/questions/28457998/swift-catransaction-synchronize-called-within-transaction-while-decoding-htm, ma la soluzione corrente utilizza una libreria esterna. –

0

Prova SwiftSoup. Questo lavoro per me.

let html = "<html><head><title>First parse</title></head><body><p>Parsed HTML into a doc.</p></body></html>" 
let doc: Document = try SwiftSoup.parse(html) 
let text: String = try doc.text() 
0

tenta di utilizzare la versione Swift3 del codice che ho trovato qui:

https://github.com/codepath/objc_ios_guides/wiki/Generating-NSAttributedString-from-HTML

  func styledHTMLwithHTML(_ HTML: String) -> String { 
       let style: String = "<meta charset=\"UTF-8\"><style> body { font-family: 'HelveticaNeue'; font-size: 20px; } b {font-family: 'MarkerFelt-Wide'; }</style>" 
       return "\(style)\(HTML)" 
      } 

      func attributedString(withHTML HTML: String) -> NSAttributedString { 
       let options: [AnyHashable: Any] = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType] 
       return try! NSAttributedString(data: HTML.data(using: String.Encoding.utf8)!, options: options as! [String : Any], documentAttributes: nil) 
      } 

      // This is a string that you might find in your model 
      var html: String = "This is <b>bold</b>" 

      // Apply some inline CSS 
      var styledHtml: String = styledHTMLwithHTML(html) 

      // Generate an attributed string from the HTML 
      var attributedText: NSAttributedString = attributedString(withHTML: styledHtml) 

      // Set the attributedText property of the UILabel 
      label.attributedText = attributedText 
Problemi correlati