Formatear texto HTML + negrita en UILabel

Interpretar un texto con etiquetas HTML no es tarea fácil en iOS. Para interpretar las etiquetas habrá que usar el...

Interpretar un texto con etiquetas HTML no es tarea fácil en iOS. Para interpretar las etiquetas habrá que usar el siguiente código:

let textFormat = try! NSAttributedString(
data: textToFormat!.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)

Si el anterior código no interpreta etiquetas <b> o <strong> (iOS 9), habrá que utilizar el siguiente código.

Añadir una extensión de NSMutableAttributedString a la clase:

extension NSMutableAttributedString {
 // Replaces the base font (typically Times) with the given font, while preserving traits like bold and italic
func setBaseFont(baseFont: UIFont, preserveFontSizes: Bool = false) {
let baseDescriptor = baseFont.fontDescriptor()
beginEditing()
enumerateAttribute(NSFontAttributeName, inRange: NSMakeRange(0, length), options: []) { object, range, stop in
if let font = object as? UIFont {
// Instantiate a font with our base font’s family, but with the current range’s traits
let traits = font.fontDescriptor().symbolicTraits
let descriptor = baseDescriptor.fontDescriptorWithSymbolicTraits(traits)
let newFont = UIFont(descriptor: descriptor, size: preserveFontSizes ? descriptor.pointSize : baseDescriptor.pointSize)
self.removeAttribute(NSFontAttributeName, range: range)
self.addAttribute(NSFontAttributeName, value: newFont, range: range)
}
}
endEditing()
}
}

Uso en viewDidLoad()

let text = NSMutableAttributedString(attributedString: textFormat)
text.setBaseFont(UIFont, preserveFontSizes: false)

PD: Enlace de interés de la librería HTMLLabel https://github.com/nicklockwood/HTMLLabel