{"_id":"5593675547f40b1700360878","tags":[],"user":{"_id":"54343147fa5527080064f43f","username":"","name":"Kai Pradel"},"__v":0,"initVersion":{"_id":"54343531bfaa3d0800c4d4af","version":"3.0"},"project":"54343170fa5527080064f449","metadata":{"title":"","description":"","image":[]},"createdAt":"2015-11-01T04:06:00.000Z","changelog":[],"body":"[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Build your own Apple TV App\"\n}\n[/block]\nThe new Apple TV could have huge implications for content producers everywhere. If the company that brought us the largest market place of apps anywhere is able to reproduce its success on TVOS, publishers should rejoice.\n\nWhile we're interested in following the evolution of the platform, we focused our time with gaining a complete understanding of the developer kit and learning how to build apps. What we discovered left us truly impressed: gone are the days of every app being written in objective-c. Apple is now providing developers with a toolset that is familiar to most - javascript and xml. With this approach, it is possible to develop a powerful tv experiences with a common web stack. With that, instead of building our own MediaSilo Apple TV app, we chose to help you build yours.\n\n[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"Goody-bye Objective-C - almost\",\n  \"body\": \"TVOs applications can be written in a common webstack with Java and XML.\"\n}\n[/block]\nThe following sample code comes complete with a MediaSilo library for retrieving and playing video content from MediaSilo. If you are a MediaSilo user already, this mean in less than 30 minutes, you could publish you own screening room or media portal on Apple TV with your own media. If you are new to MediaSilo you can still run the example code which includes access to a sample demo account.\n\n**Let's jump in:**\n\nApple is offering a new way to develop apps for the new Apple TV utilizing TVJS, TVXML, and TVMLKit. Let's explain what these abbreviations mean. TVJS is a set of JavaScript APIs for creating client-server apps using TVMLKit. TVML or Television Markup Language is used to create individual pages inside of a client-server app. The TVMLKit framework enables you to incorporate JavaScript and TVML files in your binary apps to create client-server apps.\n\nYou can download the entire project source code from GitHub [here](https://github.com/mediasilo/tvOS-demo).\n\n**Requirements**\n* Xcode 7.1 or later\n* Basic knowledge on Javascript\n* MediaSilo account (sample credentials provided below)\n[block:callout]\n{\n  \"type\": \"info\",\n  \"title\": \"MediaSilo Sandbox\",\n  \"body\": \"Feel free to use this account for testing:\\n\\n*Hostname*: tvos\\n*Username*: tvos_developer\\n*Password*: tvOSdev1\"\n}\n[/block]\n\n**Getting Started**\n\n1. If you don’t have it already, you’ll need Xcode 7.1 or later to run this. You can download Xcode 7.1 at https://developer.apple.com/xcode/download/.\n\n2. Open Xcode and create a new project using the Single View Application template from tvOS.\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/Nj1ghcqKRYaz23m9tEMU_Screen%20Shot%202015-11-03%20at%205.58.41%20PM.png\",\n        \"Screen Shot 2015-11-03 at 5.58.41 PM.png\",\n        \"800\",\n        \"612\",\n        \"#3a5c8c\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n3. Let’s simplify the template by removing the unneeded view controller file and the main storyboard from the app.\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/zgU2HQDPQL6QaNFgkGB0_Untitled-1.png\",\n        \"Untitled-1.png\",\n        \"700\",\n        \"496\",\n        \"#204a8b\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n4. Remove the Main storyboard file base name from info.plist.\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/cYajLaO4TXOxJehcWvm0_Untitled-2.png\",\n        \"Untitled-2.png\",\n        \"700\",\n        \"496\",\n        \"#a14a3e\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n5. Let’s wire up our backend. In order to communicate with our front end we need TVMLKit so be sure to import it.\n6. In order to observe changes in our application state we’ll need to change the class declaration to add the `TVApplicationControllerDelegate` protocol.\n7. We need to set up communication between our backend tvOS app and our javascript front end. To do that we’ll create a global variable `var appController: TVApplicationController?`\n8. Modify `application:didFinishLaunchingWithOptions:` according to the code found in the listing below.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var window: UIWindow?\\n    var appController: TVApplicationController?\\n    \\n    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {\\n\\n        window = UIWindow(frame: UIScreen.mainScreen().bounds)\\n\\n        let appControllerContext = TVApplicationControllerContext()\\n\\n        let TVBaseURL = \\\"http://localhost:9001/\\\"\\n        let TVBootURL = \\\"\\\\(TVBaseURL)/application.js\\\"\\n        \\n        if let javaScriptURL = NSURL(string: TVBootURL) {\\n            appControllerContext.javaScriptApplicationURL = javaScriptURL\\n        }\\n        \\n        appControllerContext.launchOptions[\\\"BASEURL\\\"] = TVBaseURL\\n        \\n        if let launchOptions = launchOptions as? [String: AnyObject] {\\n            for (kind, value) in launchOptions {\\n                appControllerContext.launchOptions[kind] = value\\n            }\\n        }\\n        \\n        appController = TVApplicationController(context: appControllerContext, window: window, delegate: self)\\n        \\n        return true\\n    }\\n    \",\n      \"language\": \"swift\"\n    }\n  ]\n}\n[/block]\n**Now, let’s move to the client side of the application**\n\n1. Create a new folder and name it “client” and add a new javascript file called “application.js”. For this tutorial we will use the stackTemplate to display a carousel and a shelf element. You can find the example template [here](https://developer.apple.com/library/prerelease/tvos/documentation/LanguagesUtilities/Conceptual/ATV_Template_Guide/StackTemplate.html#//apple_ref/doc/uid/TP40015064-CH21-SW4).\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"\\nvar DemoAPP = (function () {\\n   \\n    var stackTemplate = function() {\\n\\n        var XMLString = `<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\\n        <document>\\n            <head>\\n                <style>\\n                .darkBackgroundColor {\\n                    background-color: #171717;\\n                }\\n                .titleBanner {\\n                    tv-text-style: title1;\\n                }\\n                .subtitleBanner {\\n                    tv-text-style: title3;\\n                }\\n            </style>\\n        </head>\\n            <stackTemplate theme=\\\"dark\\\" class=\\\"darkBackgroundColor\\\">\\n            <collectionList>\\n                <carousel>\\n                    <section>\\n                        <lockup>\\n                            <img src=\\\"https://s3.amazonaws.com/thumbnails.mediasilo.com/334450782SEKR/bc1f0cb2-7da8-498c-a368-4da05e1ed221_large.jpg\\\" width=\\\"578\\\" height=\\\"260\\\" />\\n                            <title>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</title>\\n                        </lockup>\\n                    </section>\\n                </carousel>\\n                <shelf>\\n                    <header>\\n                        <title>Recent Assets</title>\\n                    </header>\\n                    <section>\\n                        <lockup>\\n                            <img src=\\\"https://s3.amazonaws.com/thumbnails.mediasilo.com/334450782SEKR/538b1dde-b73b-4d2c-b43f-5262c5243f25_large.jpg\\\" width=\\\"578\\\" height=\\\"260\\\" />\\n                            <title>Asset Title</title>\\n                        </lockup>\\n                    </section>\\n                </shelf>\\n            </collectionList>\\n        </stackTemplate>\\n        </document>`\\n\\n        var parser = new DOMParser();\\n        var domElement = parser.parseFromString(XMLString, \\\"application/xml\\\");\\n        navigationDocument.pushDocument(domElement);\\n    };\\n\\n    return {\\n\\n        stackTemplate:stackTemplate\\n    };\\n\\n})();\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n2. Now let's call the template inside of the loading method in application.js.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"App.onLaunch = function(options) {\\n\\n\\tDemoAPP.stackTemplate();\\n}\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n3. Now we need to serve our client app. An easy way to do that is by using Python's SimpleHTTPServer. From the client directory run ``` python -m SimpleHTTPServer 9001 ```.\nThis will run your client on http://localhost:9001. By reviewing the backend you’ll see that our tvOS server is already configured to find the front end here.\n\n** Go back to the Xcode and Run the app. **\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/Vj0RWcSfRmKhTSLB9am1_Pasted%20image%20at%202015_11_05%2011_32%20AM.png\",\n        \"Pasted image at 2015_11_05 11_32 AM.png\",\n        \"1072\",\n        \"674\",\n        \"#79a8b7\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n** Now, let’s make the app fetch assets from your MediaSilo account. **\n\n4.First, in your application.js file add the following variables. We’ll use the to get our video assets from the MediaSilo REST API. \n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var appUrl; // base application url\\nvar hostname = \\\"tvos\\\"; // Your MediaSilo hostname\\nvar username = \\\"tvos_developer\\\"; // Your MediaSilo username\\nvar password = \\\"tvOSdev1\\\"; // Your MediaSilo password\\nvar projectName = \\\"Season 1 - Final Cut\\\"; // The project's name we will be using on this tutorial\\nvar mediaSiloAPIUrl = \\\"https://api.mediasilo.com/v3/\\\"; // Since we're using the MediaSIlo API we'll store the root API url here\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n5. Right below the stackTemplate method let's create a function to make the request to the MediaSilo API.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \" var apiRequest = function (apiurl, doneCallback) {\\n\\n        var urlRequest = apiurl;\\n        var httpRequest = new XMLHttpRequest();\\n        httpRequest.onreadystatechange = function() {\\n\\n            //We check to see if the request finished and response is ready\\n            if (httpRequest.readyState==4 && httpRequest.status==200) {\\n\\n                var jsonData = JSON.parse(httpRequest.responseText);\\n                doneCallback( jsonData );\\n            }\\n        }\\n        httpRequest.open(\\\"GET\\\", urlRequest, true);\\n        httpRequest.setRequestHeader(\\\"Authorization\\\", \\\"Basic \\\" + btoa(username + \\\":\\\" + password));\\n        httpRequest.setRequestHeader(\\\"MediaSiloHostContext\\\", hostname);\\n        httpRequest.send();\\n    };\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n6. Here we will create a method to retrieve all the projects you have access to. Since MediaSilo stores your video assets with projects we’ll need this before we can get them.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var fetchProjects = function (doneCallback) {\\n\\n        apiRequest(mediaSiloAPIUrl + \\\"projects\\\", function(projects) {\\n\\n            doneCallback(projects);\\n\\n        });\\n\\n    };\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n7. Now that we have our projects, let’s create another method that we will use to fetch assets from a specific project.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \" var fetchAssets = function (projectId, doneCallback) {\\n\\n        apiRequest(mediaSiloAPIUrl + \\\"projects/\\\" + projectId + \\\"/assets\\\", function (assets) {\\n\\n            doneCallback(assets);\\n\\n        });\\n    };\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n8. Based on the list of assets that we have, let's dynamically generate the XML content that goes inside of the carousel.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var generateLockupCarousel = function (dataAssets) {\\n\\n        var lockupXML = \\\"\\\";\\n\\n        for (var i=0;i<dataAssets.length;i++) {\\n\\n            var asset = dataAssets[i];\\n\\n            lockupXML += '<lockup  videoURL=\\\"'+ getProxyURL(asset.derivatives) +'\\\">'\\n                + '<img src=\\\"' + asset.posterFrame +'\\\" width=\\\"1920\\\" height=\\\"800\\\" />'\\n                + '<overlay>'\\n                + ' <title class=\\\"titleBanner\\\">'+ asset.title +'</title>'\\n                + ' <subtitle allowsZooming=\\\"true\\\" class=\\\"subtitleBanner\\\">'+ asset.description +'</subtitle>'\\n                + '</overlay>'\\n                + '</lockup>';\\n\\n        }\\n        return lockupXML;\\n    };\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n9. Let’s do the same for the shelf.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var generateLockupShelf = function (dataAssets) {\\n\\n        var shelfXML = \\\"\\\";\\n\\n        for (var i=0;i<dataAssets.length;i++) {\\n\\n            var asset = dataAssets[i];\\n            shelfXML = shelfXML + '<lockup asset=\\\"' + asset.id + '\\\" videoURL=\\\"'+ getProxyURL(asset.derivatives) +'\\\">'\\n                + '<img src=\\\"' + asset.posterFrame +'\\\" width=\\\"578\\\" height=\\\"260\\\" />'\\n                + ' <title>'+ asset.title +'</title>'\\n                + '</lockup>';\\n\\n        }\\n        return shelfXML;\\n    };\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n10. Here is the method we are using to display video asset.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var playVideo = function( event ) {\\n\\n        var ele = event.target,\\n            videoURL = ele.getAttribute(\\\"videoURL\\\");\\n\\n        if(videoURL) {\\n\\n            var player = new Player();\\n            var playlist = new Playlist();\\n            var mediaItem = new MediaItem(\\\"video\\\", videoURL);\\n\\n            player.playlist = playlist;\\n            player.playlist.push(mediaItem);\\n            player.present();\\n        }\\n    }\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n11. We can now pass in our carousel and shelf to our stackTemplate so it can build itself dynamically. Also add an event listener on the domElement to respond when a video is selected to display it.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"var stackTemplate = function(carousel, shelf) {\\n\\n        var XMLString = `<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" ?>\\n        <document>\\n            <head>\\n                <style>\\n                .darkBackgroundColor {\\n                    background-color: #171717;\\n                }\\n                .titleBanner {\\n                    tv-text-style: title1;\\n                }\\n                .subtitleBanner {\\n                    tv-text-style: title3;\\n                }\\n            </style>\\n        </head>\\n            <stackTemplate theme=\\\"dark\\\" class=\\\"darkBackgroundColor\\\">\\n            <collectionList>\\n                <carousel>\\n                    <section>\\n                        ${carousel}\\n                    </section>\\n                </carousel>\\n                <shelf>\\n                    <header>\\n                        <title>Recent Assets</title>\\n                    </header>\\n                    <section>\\n                        ${shelf}\\n                    </section>\\n                </shelf>\\n            </collectionList>\\n        </stackTemplate>\\n        </document>`\\n\\n        var parser = new DOMParser();\\n        var domElement = parser.parseFromString(XMLString, \\\"application/xml\\\");\\n        domElement.addEventListener(\\\"select\\\", DemoAPP.playVideo.bind(this), false);\\n        navigationDocument.pushDocument(domElement);\\n    };\\n\\n\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]\n12. Let’s go back to the method App.onLaunch and make some changes to it. First, let's call the the method that we just created, fetchProjects. This loops through the results and finds the project name we defined in the variable projectName.  After that we will fetch all the assets on this project.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"App.onLaunch = function(options) {\\n\\n    DemoAPP.fetchProjects(function(projects) {\\n\\n        for (var i = 0; i < projects.length; i++) {\\n\\n            var project = projects[i];\\n\\n            if (project.name == projectName) {\\n\\n                DemoAPP.fetchAssets(project.id, function(assets) {\\n\\n                    var xmlCarousel = DemoAPP.generateLockupCarousel(assets);\\n                    var xmlShelf = DemoAPP.generateLockupShelf(assets);\\n                    \\n                    DemoAPP.stackTemplate(xmlCarousel, xmlShelf);\\n\\n                });\\n            }\\n        }\\n    });\\n\\n}\",\n      \"language\": \"javascript\"\n    }\n  ]\n}\n[/block]","slug":"updates","title":"Building Your Own tvOS Application"}

Building Your Own tvOS Application


[block:api-header] { "type": "basic", "title": "Build your own Apple TV App" } [/block] The new Apple TV could have huge implications for content producers everywhere. If the company that brought us the largest market place of apps anywhere is able to reproduce its success on TVOS, publishers should rejoice. While we're interested in following the evolution of the platform, we focused our time with gaining a complete understanding of the developer kit and learning how to build apps. What we discovered left us truly impressed: gone are the days of every app being written in objective-c. Apple is now providing developers with a toolset that is familiar to most - javascript and xml. With this approach, it is possible to develop a powerful tv experiences with a common web stack. With that, instead of building our own MediaSilo Apple TV app, we chose to help you build yours. [block:callout] { "type": "info", "title": "Goody-bye Objective-C - almost", "body": "TVOs applications can be written in a common webstack with Java and XML." } [/block] The following sample code comes complete with a MediaSilo library for retrieving and playing video content from MediaSilo. If you are a MediaSilo user already, this mean in less than 30 minutes, you could publish you own screening room or media portal on Apple TV with your own media. If you are new to MediaSilo you can still run the example code which includes access to a sample demo account. **Let's jump in:** Apple is offering a new way to develop apps for the new Apple TV utilizing TVJS, TVXML, and TVMLKit. Let's explain what these abbreviations mean. TVJS is a set of JavaScript APIs for creating client-server apps using TVMLKit. TVML or Television Markup Language is used to create individual pages inside of a client-server app. The TVMLKit framework enables you to incorporate JavaScript and TVML files in your binary apps to create client-server apps. You can download the entire project source code from GitHub [here](https://github.com/mediasilo/tvOS-demo). **Requirements** * Xcode 7.1 or later * Basic knowledge on Javascript * MediaSilo account (sample credentials provided below) [block:callout] { "type": "info", "title": "MediaSilo Sandbox", "body": "Feel free to use this account for testing:\n\n*Hostname*: tvos\n*Username*: tvos_developer\n*Password*: tvOSdev1" } [/block] **Getting Started** 1. If you don’t have it already, you’ll need Xcode 7.1 or later to run this. You can download Xcode 7.1 at https://developer.apple.com/xcode/download/. 2. Open Xcode and create a new project using the Single View Application template from tvOS. [block:image] { "images": [ { "image": [ "https://files.readme.io/Nj1ghcqKRYaz23m9tEMU_Screen%20Shot%202015-11-03%20at%205.58.41%20PM.png", "Screen Shot 2015-11-03 at 5.58.41 PM.png", "800", "612", "#3a5c8c", "" ] } ] } [/block] 3. Let’s simplify the template by removing the unneeded view controller file and the main storyboard from the app. [block:image] { "images": [ { "image": [ "https://files.readme.io/zgU2HQDPQL6QaNFgkGB0_Untitled-1.png", "Untitled-1.png", "700", "496", "#204a8b", "" ] } ] } [/block] 4. Remove the Main storyboard file base name from info.plist. [block:image] { "images": [ { "image": [ "https://files.readme.io/cYajLaO4TXOxJehcWvm0_Untitled-2.png", "Untitled-2.png", "700", "496", "#a14a3e", "" ] } ] } [/block] 5. Let’s wire up our backend. In order to communicate with our front end we need TVMLKit so be sure to import it. 6. In order to observe changes in our application state we’ll need to change the class declaration to add the `TVApplicationControllerDelegate` protocol. 7. We need to set up communication between our backend tvOS app and our javascript front end. To do that we’ll create a global variable `var appController: TVApplicationController?` 8. Modify `application:didFinishLaunchingWithOptions:` according to the code found in the listing below. [block:code] { "codes": [ { "code": "var window: UIWindow?\n var appController: TVApplicationController?\n \n func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {\n\n window = UIWindow(frame: UIScreen.mainScreen().bounds)\n\n let appControllerContext = TVApplicationControllerContext()\n\n let TVBaseURL = \"http://localhost:9001/\"\n let TVBootURL = \"\\(TVBaseURL)/application.js\"\n \n if let javaScriptURL = NSURL(string: TVBootURL) {\n appControllerContext.javaScriptApplicationURL = javaScriptURL\n }\n \n appControllerContext.launchOptions[\"BASEURL\"] = TVBaseURL\n \n if let launchOptions = launchOptions as? [String: AnyObject] {\n for (kind, value) in launchOptions {\n appControllerContext.launchOptions[kind] = value\n }\n }\n \n appController = TVApplicationController(context: appControllerContext, window: window, delegate: self)\n \n return true\n }\n ", "language": "swift" } ] } [/block] **Now, let’s move to the client side of the application** 1. Create a new folder and name it “client” and add a new javascript file called “application.js”. For this tutorial we will use the stackTemplate to display a carousel and a shelf element. You can find the example template [here](https://developer.apple.com/library/prerelease/tvos/documentation/LanguagesUtilities/Conceptual/ATV_Template_Guide/StackTemplate.html#//apple_ref/doc/uid/TP40015064-CH21-SW4). [block:code] { "codes": [ { "code": "\nvar DemoAPP = (function () {\n \n var stackTemplate = function() {\n\n var XMLString = `<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <document>\n <head>\n <style>\n .darkBackgroundColor {\n background-color: #171717;\n }\n .titleBanner {\n tv-text-style: title1;\n }\n .subtitleBanner {\n tv-text-style: title3;\n }\n </style>\n </head>\n <stackTemplate theme=\"dark\" class=\"darkBackgroundColor\">\n <collectionList>\n <carousel>\n <section>\n <lockup>\n <img src=\"https://s3.amazonaws.com/thumbnails.mediasilo.com/334450782SEKR/bc1f0cb2-7da8-498c-a368-4da05e1ed221_large.jpg\" width=\"578\" height=\"260\" />\n <title>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</title>\n </lockup>\n </section>\n </carousel>\n <shelf>\n <header>\n <title>Recent Assets</title>\n </header>\n <section>\n <lockup>\n <img src=\"https://s3.amazonaws.com/thumbnails.mediasilo.com/334450782SEKR/538b1dde-b73b-4d2c-b43f-5262c5243f25_large.jpg\" width=\"578\" height=\"260\" />\n <title>Asset Title</title>\n </lockup>\n </section>\n </shelf>\n </collectionList>\n </stackTemplate>\n </document>`\n\n var parser = new DOMParser();\n var domElement = parser.parseFromString(XMLString, \"application/xml\");\n navigationDocument.pushDocument(domElement);\n };\n\n return {\n\n stackTemplate:stackTemplate\n };\n\n})();", "language": "javascript" } ] } [/block] 2. Now let's call the template inside of the loading method in application.js. [block:code] { "codes": [ { "code": "App.onLaunch = function(options) {\n\n\tDemoAPP.stackTemplate();\n}", "language": "javascript" } ] } [/block] 3. Now we need to serve our client app. An easy way to do that is by using Python's SimpleHTTPServer. From the client directory run ``` python -m SimpleHTTPServer 9001 ```. This will run your client on http://localhost:9001. By reviewing the backend you’ll see that our tvOS server is already configured to find the front end here. ** Go back to the Xcode and Run the app. ** [block:image] { "images": [ { "image": [ "https://files.readme.io/Vj0RWcSfRmKhTSLB9am1_Pasted%20image%20at%202015_11_05%2011_32%20AM.png", "Pasted image at 2015_11_05 11_32 AM.png", "1072", "674", "#79a8b7", "" ] } ] } [/block] ** Now, let’s make the app fetch assets from your MediaSilo account. ** 4.First, in your application.js file add the following variables. We’ll use the to get our video assets from the MediaSilo REST API. [block:code] { "codes": [ { "code": "var appUrl; // base application url\nvar hostname = \"tvos\"; // Your MediaSilo hostname\nvar username = \"tvos_developer\"; // Your MediaSilo username\nvar password = \"tvOSdev1\"; // Your MediaSilo password\nvar projectName = \"Season 1 - Final Cut\"; // The project's name we will be using on this tutorial\nvar mediaSiloAPIUrl = \"https://api.mediasilo.com/v3/\"; // Since we're using the MediaSIlo API we'll store the root API url here", "language": "javascript" } ] } [/block] 5. Right below the stackTemplate method let's create a function to make the request to the MediaSilo API. [block:code] { "codes": [ { "code": " var apiRequest = function (apiurl, doneCallback) {\n\n var urlRequest = apiurl;\n var httpRequest = new XMLHttpRequest();\n httpRequest.onreadystatechange = function() {\n\n //We check to see if the request finished and response is ready\n if (httpRequest.readyState==4 && httpRequest.status==200) {\n\n var jsonData = JSON.parse(httpRequest.responseText);\n doneCallback( jsonData );\n }\n }\n httpRequest.open(\"GET\", urlRequest, true);\n httpRequest.setRequestHeader(\"Authorization\", \"Basic \" + btoa(username + \":\" + password));\n httpRequest.setRequestHeader(\"MediaSiloHostContext\", hostname);\n httpRequest.send();\n };", "language": "javascript" } ] } [/block] 6. Here we will create a method to retrieve all the projects you have access to. Since MediaSilo stores your video assets with projects we’ll need this before we can get them. [block:code] { "codes": [ { "code": "var fetchProjects = function (doneCallback) {\n\n apiRequest(mediaSiloAPIUrl + \"projects\", function(projects) {\n\n doneCallback(projects);\n\n });\n\n };", "language": "javascript" } ] } [/block] 7. Now that we have our projects, let’s create another method that we will use to fetch assets from a specific project. [block:code] { "codes": [ { "code": " var fetchAssets = function (projectId, doneCallback) {\n\n apiRequest(mediaSiloAPIUrl + \"projects/\" + projectId + \"/assets\", function (assets) {\n\n doneCallback(assets);\n\n });\n };", "language": "javascript" } ] } [/block] 8. Based on the list of assets that we have, let's dynamically generate the XML content that goes inside of the carousel. [block:code] { "codes": [ { "code": "var generateLockupCarousel = function (dataAssets) {\n\n var lockupXML = \"\";\n\n for (var i=0;i<dataAssets.length;i++) {\n\n var asset = dataAssets[i];\n\n lockupXML += '<lockup videoURL=\"'+ getProxyURL(asset.derivatives) +'\">'\n + '<img src=\"' + asset.posterFrame +'\" width=\"1920\" height=\"800\" />'\n + '<overlay>'\n + ' <title class=\"titleBanner\">'+ asset.title +'</title>'\n + ' <subtitle allowsZooming=\"true\" class=\"subtitleBanner\">'+ asset.description +'</subtitle>'\n + '</overlay>'\n + '</lockup>';\n\n }\n return lockupXML;\n };", "language": "javascript" } ] } [/block] 9. Let’s do the same for the shelf. [block:code] { "codes": [ { "code": "var generateLockupShelf = function (dataAssets) {\n\n var shelfXML = \"\";\n\n for (var i=0;i<dataAssets.length;i++) {\n\n var asset = dataAssets[i];\n shelfXML = shelfXML + '<lockup asset=\"' + asset.id + '\" videoURL=\"'+ getProxyURL(asset.derivatives) +'\">'\n + '<img src=\"' + asset.posterFrame +'\" width=\"578\" height=\"260\" />'\n + ' <title>'+ asset.title +'</title>'\n + '</lockup>';\n\n }\n return shelfXML;\n };", "language": "javascript" } ] } [/block] 10. Here is the method we are using to display video asset. [block:code] { "codes": [ { "code": "var playVideo = function( event ) {\n\n var ele = event.target,\n videoURL = ele.getAttribute(\"videoURL\");\n\n if(videoURL) {\n\n var player = new Player();\n var playlist = new Playlist();\n var mediaItem = new MediaItem(\"video\", videoURL);\n\n player.playlist = playlist;\n player.playlist.push(mediaItem);\n player.present();\n }\n }", "language": "javascript" } ] } [/block] 11. We can now pass in our carousel and shelf to our stackTemplate so it can build itself dynamically. Also add an event listener on the domElement to respond when a video is selected to display it. [block:code] { "codes": [ { "code": "var stackTemplate = function(carousel, shelf) {\n\n var XMLString = `<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n <document>\n <head>\n <style>\n .darkBackgroundColor {\n background-color: #171717;\n }\n .titleBanner {\n tv-text-style: title1;\n }\n .subtitleBanner {\n tv-text-style: title3;\n }\n </style>\n </head>\n <stackTemplate theme=\"dark\" class=\"darkBackgroundColor\">\n <collectionList>\n <carousel>\n <section>\n ${carousel}\n </section>\n </carousel>\n <shelf>\n <header>\n <title>Recent Assets</title>\n </header>\n <section>\n ${shelf}\n </section>\n </shelf>\n </collectionList>\n </stackTemplate>\n </document>`\n\n var parser = new DOMParser();\n var domElement = parser.parseFromString(XMLString, \"application/xml\");\n domElement.addEventListener(\"select\", DemoAPP.playVideo.bind(this), false);\n navigationDocument.pushDocument(domElement);\n };\n\n", "language": "javascript" } ] } [/block] 12. Let’s go back to the method App.onLaunch and make some changes to it. First, let's call the the method that we just created, fetchProjects. This loops through the results and finds the project name we defined in the variable projectName. After that we will fetch all the assets on this project. [block:code] { "codes": [ { "code": "App.onLaunch = function(options) {\n\n DemoAPP.fetchProjects(function(projects) {\n\n for (var i = 0; i < projects.length; i++) {\n\n var project = projects[i];\n\n if (project.name == projectName) {\n\n DemoAPP.fetchAssets(project.id, function(assets) {\n\n var xmlCarousel = DemoAPP.generateLockupCarousel(assets);\n var xmlShelf = DemoAPP.generateLockupShelf(assets);\n \n DemoAPP.stackTemplate(xmlCarousel, xmlShelf);\n\n });\n }\n }\n });\n\n}", "language": "javascript" } ] } [/block]