Force view to reload tvml content on Apple TV/tvos

2019-07-05 05:22发布

问题:

I have been working on dynamically generating tvml-templates with very frequently changing content for a tvOS app on Apple TV. Generating the templates works fine, however I have not been able to get the app to update/reload the content of a template when navigating back and forth between views or leaving and reentering the app. Only rebooting seems to reload the tvml template.

回答1:

Your template will refresh itself automatically whenever you manipulate the TVML within the template document.

If you maintain a reference to the document like so:

var myDoc;

resourceLoader.loadResource(templateURL,
   function(resource) {
     if (resource) {
       myDoc = self.makeDocument(resource);
     });
   }                         

you can manipulate the TVML using myDoc and your view will automatically change.

So if your template document includes a "collectionList" and you were to run this code:

//Removes the child elements of the first collectionList
var collectionLists = myDoc.getElementsByTagName("collectionList");
var collectionList = collectionLists.item(0);
while (collectionList.firstChild) {
   collectionList.removeChild(collectionList.firstChild);
}

your view would no longer display the UI elements within the collectionList. The view will refresh itself the moment the code is run.



回答2:

The answer by @shirefriendship pointed my in the right direction (thank you!). As another example, if you wanted to change the text of a single element in a template (such as the description), you would need to use the innerHTML property:

function changeDescription(incomingString) {
    console.log("inside the change description function")
    if (incomingString) {
        var theDescription = myDoc.getElementsByTagName("description").item(0);
        theDescription.innerHTML = incomingString;
    }
}

This changes the description immediately to the viewer.



回答3:

If you are using atvjs framework, you can easily create and navigate to dynamic pages which are regenerated while navigating.

ATV.Page.create({
    name: 'home',
    url: 'path/to/your/api/that/returns/json',
    template: your_template_function
});
// navigate to your page
ATV.Navigation.navigate('home');


回答4:

Set this in the header of your API:

Cache-Control:no-cache

Got it from Apple Docs: https://developer.apple.com/library/tvos/documentation/General/Conceptual/AppleTV_PG/YourFirstAppleTVApp.html

IMPORTANT

When serving JavaScript and XML files from your web server, you often need to ensure that any changes to your pages are always visible to the client app. To do this, your server must ensure that the client does not cache any of the pages. When your server responds to an HTTP request for a page that should not be cached, the server should include Cache-Control:no-cache in the HTTP response header.