Search code examples
javascriptjsonyoutube-apititaniumappcelerator

Titanium Appcelerator parse Youtube JSON with API


I did a research over the forums and i got confused. My demo project was created with Alloy MVC. I want to parse a JSON from Youtube API with the top releated videos of Cooking for example, and show them in a TableView. Can anyone give me instructions how to do it? I'm a newcomer.

This is my code what i've done so far:

Videos XML

<Alloy>
<Window class="container">
<View id="main" onClick="youtubeFeed">
   <Label class="header">YouTube Channel</Label>
            <TableView id="results">

            </TableView>            
        </View>
    </Window>
</Alloy>

Videos.js

function youtubeFeed () {

var apiKey = 'MY_API_KEY';
var perPage = 6;
var search = "Cooking";
var description;
var val;
var id;
var category = "News";

var query = 'https://www.googleapis.com/youtube/v3/search?part=snippet&q=search&maxResults=per_page&videoCategoryId=category&safesearch=strict&key=apikey';
var response = JSON.parse(this.responseText);

require("/api").create({
    url: query,
    type: "GET",
    success: onSuccess,
    error: onError
});

function onSuccess(e){
    console.log(e.data);
}

function onError(e){
    console.log("error");
}

}

Solution

  • you need to call the actual API url with the help of xhr. For the beginning have a look at https://github.com/m1ga/titanium-libraries/blob/master/api.js

    Create a lib folder in your projectname/app/ folder and place the js file there and then call it like this inside yor function:

    require("/api").create({
        url: query,
        type: "GET",
        success: onSuccess,
        error: onError
    });
    
    function onSuccess(e){
        console.log(e.data);
    }
    
    function onError(e){
        console.log("error");
    }
    

    and make sure your query string is right. It looks like you've took a php example because it uses $ and a . at the end to concatenate.