Convertir HTML a NSAttributedString en iOS
Estoy usando una instancia de UIWebView
para procesar algún texto y colorearlo correctamente, da el resultado como HTML pero en lugar de mostrarlo en el UIWebView
Quiero mostrarlo usando Core Text
con un NSAttributedString
.
Soy capaz de crear y dibujar el NSAttributedString
pero no estoy seguro de cómo puedo convertir y mapear el HTML en la cadena atribuida.
Entiendo que bajo Mac OS X NSAttributedString
tiene un método initWithHTML:
pero esto fue una adición solo para Mac y no está disponible para iOS.
También sé que hay es una pregunta similar a esta, pero no tenía respuestas, aunque lo intentaría de nuevo y ver si alguien ha creado una manera de hacer esto y si es así, si podrían compartirlo.
13 answers
En iOS 7, UIKit agregó un initWithData: options: documentAttributes: error: método que puede inicializar un NSAtttributedString usando HTML, por ejemplo:
[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
documentAttributes:nil error:nil];
En Swift:
let htmlData = NSString(string: details).data(using: String.Encoding.unicode.rawValue)
let options = [NSAttributedString.DocumentReadingOptionKey.documentType:
NSAttributedString.DocumentType.html]
let attributedString = try? NSMutableAttributedString(data: htmlData ?? Data(),
options: options,
documentAttributes: nil)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-31 12:53:39
Hay un trabajo en progreso adición de código abierto a NSAttributedString por Oliver Drobnik en Github. Utiliza NSScanner para el análisis HTML.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-09 12:58:16
¡Crear un NSAttributedString desde HTML debe hacerse en el hilo principal!
Actualización: Resulta que la representación HTML de NSAttributedString depende de WebKit bajo el capó, y debe ejecutarse en el hilo principal o ocasionalmente bloqueará la aplicación con un SIGTRAP.
Registro de bloqueos de New Relic:
A continuación se muestra una cadena actualizada thread-safe Swift 2 extensión:
extension String {
func attributedStringFromHTML(completionBlock:NSAttributedString? ->()) {
guard let data = dataUsingEncoding(NSUTF8StringEncoding) else {
print("Unable to decode data from html string: \(self)")
return completionBlock(nil)
}
let options = [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: NSNumber(unsignedInteger:NSUTF8StringEncoding)]
dispatch_async(dispatch_get_main_queue()) {
if let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) {
completionBlock(attributedString)
} else {
print("Unable to create attributed string from html string: \(self)")
completionBlock(nil)
}
}
}
}
Uso:
let html = "<center>Here is some <b>HTML</b></center>"
html.attributedStringFromHTML { attString in
self.bodyLabel.attributedText = attString
}
Salida:
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-24 20:56:02
Extensión del inicializador swift en NSAttributedString
Mi inclinación era agregar esto como una extensión a NSAttributedString
en lugar de String
. Lo probé como una extensión estática y un inicializador. Prefiero el inicializador que es lo que he incluido a continuación.
Swift 4
internal convenience init?(html: String) {
guard let data = html.data(using: String.Encoding.utf16, allowLossyConversion: false) else {
return nil
}
guard let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) else {
return nil
}
self.init(attributedString: attributedString)
}
Swift 3
extension NSAttributedString {
internal convenience init?(html: String) {
guard let data = html.data(using: String.Encoding.utf16, allowLossyConversion: false) else {
return nil
}
guard let attributedString = try? NSMutableAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) else {
return nil
}
self.init(attributedString: attributedString)
}
}
Ejemplo
let html = "<b>Hello World!</b>"
let attributedString = NSAttributedString(html: html)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-12-03 07:50:03
Esta es una extensión String
escrita en Swift para devolver una cadena HTML como NSAttributedString
.
extension String {
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.dataUsingEncoding(NSUTF16StringEncoding, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) else { return nil }
return html
}
}
Utilizar,
label.attributedText = "<b>Hello</b> \u{2022} babe".htmlAttributedString()
En lo anterior, he agregado deliberadamente un unicode \u2022 para mostrar que renderiza unicode correctamente.
Un trivial: La codificación predeterminada que utiliza NSAttributedString
es NSUTF16StringEncoding
(¡no UTF8!).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-25 03:23:33
Swift 3.0 Xcode 8 Version
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) else { return nil }
return html
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-28 18:19:48
La única solución que tiene ahora es analizar el HTML, construir algunos nodos con los atributos point/font/etc dados, luego combinarlos en un NSAttributedString. Es mucho trabajo, pero si se hace correctamente, puede ser reutilizable en el futuro.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-11-18 17:42:03
Hizo algunas modificaciones en la solución de Andrew y actualizó el código a Swift 3:
Este código ahora usa UITextView como self
y puede heredar su fuente original, tamaño de fuente y color de texto
Nota: toHexString()
es la extensión de aquí
extension UITextView {
func setAttributedStringFromHTML(_ htmlCode: String, completionBlock: @escaping (NSAttributedString?) ->()) {
let inputText = "\(htmlCode)<style>body { font-family: '\((self.font?.fontName)!)'; font-size:\((self.font?.pointSize)!)px; color: \((self.textColor)!.toHexString()); }</style>"
guard let data = inputText.data(using: String.Encoding.utf16) else {
print("Unable to decode data from html string: \(self)")
return completionBlock(nil)
}
DispatchQueue.main.async {
if let attributedString = try? NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) {
self.attributedText = attributedString
completionBlock(attributedString)
} else {
print("Unable to create attributed string from html string: \(self)")
completionBlock(nil)
}
}
}
}
Ejemplo de uso:
mainTextView.setAttributedStringFromHTML("<i>Hello world!</i>") { _ in }
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:34
Swift 4
- Inicializador de conveniencia NSAttributedString
- Sin protectores adicionales
- lanza error
extension NSAttributedString {
convenience init(htmlString html: String) throws {
try self.init(data: Data(html.utf8), options: [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
], documentAttributes: nil)
}
}
Uso
UILabel.attributedText = try? NSAttributedString(htmlString: "<strong>Hello</strong> World!")
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-30 19:43:53
La solución anterior es correcta.
[[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUTF8StringEncoding]
options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
documentAttributes:nil error:nil];
Pero la aplicación wioll se bloquea si la está ejecutando en ios 8.1,2 o 3.
Para evitar el bloqueo, lo que puede hacer es : ejecutar esto en una cola. Para que siempre esté en el hilo principal.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-30 07:17:41
El uso de NSHTMLTextDocumentType es lento y es difícil controlar los estilos. Le sugiero que pruebe mi biblioteca que se llama Atributika. Tiene su propio analizador HTML muy rápido. También puede tener cualquier nombre de etiqueta y definir cualquier estilo para ellos.
Ejemplo:
let str = "<strong>Hello</strong> World!".style(tags:
Style("strong").font(.boldSystemFont(ofSize: 15))).attributedString
label.attributedText = str
Lo puedes encontrar aquí https://github.com/psharanda/Atributika
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-22 19:51:58
Swift 3:
Pruebe este:
extension String {
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(
data: data,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil) else { return nil }
return html
}
}
Y para usar:
let str = "<h1>Hello bro</h1><h2>Come On</h2><h3>Go sis</h3><ul><li>ME 1</li><li>ME 2</li></ul> <p>It is me bro , remember please</p>"
self.contentLabel.attributedText = str.htmlAttributedString()
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-26 22:46:50
Extensiones útiles
Inspirado por este hilo, un pod, y el ejemplo de ObjC de Erica Sadun en iOS Gourmet Cookbook p. 80, escribí una extensión en String
y en NSAttributedString
para ir y venir entre HTML plain-strings y NSAttributedStrings y viceversa on en GitHub aquí, que he encontrado útil.
Las firmas son (de nuevo, código completo en un Gist, enlace anterior):
extension NSAttributedString {
func encodedString(ext: DocEXT) -> String?
static func fromEncodedString(_ eString: String, ext: DocEXT) -> NSAttributedString?
static func fromHTML(_ html: String) -> NSAttributedString? // same as above, where ext = .html
}
extension String {
func attributedString(ext: DocEXT) -> NSAttributedString?
}
enum DocEXT: String { case rtfd, rtf, htm, html, txt }
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-19 12:02:53