Showing HTML content in tvOS

David Cordero
2 min readAug 17, 2020

This post was original published in dcordero.me, where you will always find the most updated, and free of spyware version of all my posts.

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() {
super.viewDidLoad()

let html = """
<!DOCTYPE html>
<head>
<style>
h1 {
color:red;
font-size: 200%;
}
p {
color:blue;
font-size: xx-large;
}
</style>
</head>
<body>
<h1>Chiquito Ipsum</h1>
<p>
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.
</p>
<p>
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.
</p>
</body>
</html>
"""

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
view.addSubview(textView)

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
}
}

--

--

David Cordero

iOS and tvOS developer at Zattoo. Passionate about coding and lifelong learning.