Get started building TVML/TVJS apps on Apple tvOS

Apple give you two options of building tvOS apps — build natively using UIKit and other familiar iOS frameworks, or use a HTML-like TVML markup language along with javascript and stylesheets.


The TVML route is quite powerful — you can easily build apps that allow you to navigate content and playback media without having to write much native code at all. This allows you to generate the javascript and TVML to run on the device server-side, thus giving you the flexibility of updating the content layout and navigation without re-deploying your app.


A simple playlist browser in TVML

Where is my console.log()?

One of the first things you will realise is that you cannot easily debug your TVJS because there is no console.log()!

In order to implement this, add the following function to your AppDelegate:

This creates a console.log() function within the JSContext that the TVML app runs in — it’s all JSCore under the hood. Unfortunately, a Swift function does not conform to AnyObject, so we cannot directly assign it to a JSValue. In order to get around this, we use the new @convention directive to define an Objective-C block in swift, which can then be cast to AnyObject using unsafeBitCast()

Hyperlinking

There is no built in hyperlinking in TVML. In order to link from one page to another, you will need to attach event listeners to DOM nodes and handle that yourself.

The basic approach is to intercept loading of the TVML, parse it using DOMParser and attach an event listener for the ‘select’ event on the whole document. The following class allows you to do just this:

To wire this up to your application, you just need to load your home page:

When the user selects an element, if it contains a href, that link will be loaded and pushed onto the navigation stack. This is by no means all you can do with TVML, but these are the basics that helped us build a prototype app in just a few hours.

Documentation

There is some good Apple documentation, but there is not a lot around on StackOverflow and other such sites (yet). Some good documents to start with are: