David Cordero

Showing HTML content in tvOS

Published on 15 Jun 2020

If you ever tried to display HTML content in tvOS, you might have discovered that it is not as easy as initially expected.

That is because there is no web browser, UIWebView, or even WKWebView available in tvOS.

Nevertheless, there is an alternative solution that can be useful to present simple HTML content as Term and Conditions, Privacy Policies, etc…

The idea is to use an instance of UITextView with an attributed String with HTML Doctype.

Here you can find the implementation of the previous preview image.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        let html = """
            <!DOCTYPE html>
                  h1 {
                    font-size: 200%;
                  p {
                    font-size: xx-large;
            <h1>Chiquito Ipsum</h1>
            Lorem fistrum te voy a borrar el cerito fistro al ataquerl ese que llega torpedo ese hombree. No puedor a peich de la pradera torpedo al ataquerl ese pedazo de ese hombree la caidita se calle uste. Se calle ustee mamaar hasta luego Lucas quietooor fistro ahorarr. Ahorarr ese pedazo de apetecan no te digo trigo por no llamarte Rodrigor jarl sexuarl fistro a gramenawer papaar papaar ese que llega. Fistro torpedo llevame al sircoo jarl ahorarr fistro no te digo trigo por no llamarte Rodrigor pupita llevame al sircoo te va a hase pupitaa sexuarl.
            Fistro diodeno te va a hase pupitaa fistro a gramenawer. Diodenoo mamaar diodenoo amatomaa de la pradera apetecan. Papaar papaar amatomaa pupita diodeno. A peich quietooor ahorarr pecador torpedo torpedo me cago en tus muelas quietooor. Diodenoo que dise usteer se calle ustee apetecan. No te digo trigo por no llamarte Rodrigor ese pedazo de pecador diodeno amatomaa mamaar. Me cago en tus muelas que dise usteer amatomaa de la pradera quietooor.
        let stringData = html.data(using: String.Encoding.utf8, allowLossyConversion: true)
        let attributedString = try? NSAttributedString(
            data: stringData!,
            options: [.documentType: NSAttributedString.DocumentType.html],
            documentAttributes: nil)
        let textView = UITextView()
        textView.attributedText = attributedString
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        textView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        textView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        textView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true