Skip to content

Instantly share code, notes, and snippets.

@bob-sims
Created December 4, 2011 12:32
Show Gist options
  • Save bob-sims/1430088 to your computer and use it in GitHub Desktop.
Save bob-sims/1430088 to your computer and use it in GitHub Desktop.
My take on retrieving YouTube JSON feed by CommonJS module for Ti Mobile, remains work in progress.
// To call, use this statement in app.js:
// require('fetchYouTubeJSON').fetchJSONData('https://gdata.youtube.com/feeds/api/users/...');
// fires app-level event to return data, use to populate TableView or similar
//
// maybe add some cache features? http://pastie.org/1541768
// http://pastebin.com/Eq1DLsdP
// once again, ripping from the talented @skypanther
exports.fetchYouTubeData = function(url) {
// Pulls the JSON feed data and returns it to caller
var xhr = Titanium.Network.createHTTPClient();
// default JSON feed url
url = (url) ? url : "https://gdata.youtube.com/feeds/api/users/NATOACT/uploads?alt=json&v=2&max-results=10";
xhr.open('GET',url);
xhr.setRequestHeader('User-Agent', 'mobile agent')
xhr.send();
xhr.onload = function() {
// Data is returned as JSON, start parsing
Ti.API.info('Got data!');
var jsonObject = JSON.parse(this.responseText);
Ti.API.info('length: '+jsonObject.feed.entry.length);
var data = [];
// begin looping through videos
for (var i = 0; i < jsonObject.feed.entry.length; i++) {
var idArray = jsonObject.feed.entry[i].id.$t.split('video:');
var movieId = idArray[1];
data.push({
videoTitle: jsonObject.feed.entry[i].title.$t, //video title
videoLink: "http://www.youtube.com/embed/" + movieId+ "?av=1&autoplay=1",
});
}
/*
for (var i = 0; i<data.length; i++) {
Ti.API.info(data[i].postTitle);
} */
// fire an app-level event to notify the UI that the JSON data is available
Ti.App.fireEvent('net:youTubeDataReturned',{
feedTitle: jsonObject.feed.title.$t,
dateUpdated: jsonObject.feed.updated.$t,
blogPosts: data
});
};
xhr.onerror = function(e) {
// should do something more robust
Titanium.API.info(e.error);
};
}; // end getJSONData()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment