The use of RSS and ATOM feeds is common among Enterprise apps that update content periodically. You can use the techniques demonstrated in this recipe to publish content from your organization or a third party. Many companies use this approach to provide their employees with current news and updates regarding their organization or industry.
In this recipe, an RSS feed from fastcompany.com is consumed and displayed in a Ti.UI.TableView
for the user to review and launch their browser to read the details.
This recipe uses the rss2Objects
CommonJS module. This module and other code assets can be downloaded from the source code provided by the book. Installing this module into your project is straightforward. Simply copy the rss2objects.js
file into your project, as shown in the following screenshot:
Once you've added the rss2objects.js
file to your project, you need to create your application namespaces in the app.js
file and use require
to import the module into your code, as demonstrated in the following code block:
//Create our application namespace var my = { reader : require('rss2objects'), isAndroid : ( Ti.Platform.osname === 'android'), rssTestUrl : "http://www.fastcompany.com/rss.xml" };
The demonstration app for this recipe provides two Ti.UI.Button
controls to illustrate different techniques for fetching RSS results, and a Ti.UI.TableView
to display the articles.
Ti.UI.Window
to attach all UI elements onto:var win = Ti.UI.createWindow({ backgroundColor:'#fff' });
var yqlButton = Ti.UI.createButton({ title:"Load Using YQL",left:0 , width: 140, height:40, top:90 }); win.add(yqlButton);
var xmlButton = Ti.UI.createButton({ title:"Load Using XML",right:0 , width: 140,height:40, top:90 }); win.add(xmlButton);
Ti.TableView
is added to display the RSS articles:var tableView = Ti.UI.createTableView({ top:120, bottom: 0, width:Ti.UI.FILL }); win.add(tableView);
Using Yahoo's YQL platform is a convenient way to read an RSS feed. YQL has two additional benefits over conventional XML parsing. The first benefit is YQL normalizes the feed output for you. The second benefit is Yahoo will convert the RSS stream to JSON. The downside to YQL is it will reduce download speeds due to the need to proxy the feed through Yahoo's servers.
This snippet demonstrates how to call the yqlQuery
method of the rss2Objects
module. The yqlQuery
method takes two arguments: the first is the URL of the RSS feed you wish to read, and the second is a callback used to provide the feed item results.
yqlButton.addEventListener('click',function(e){ my.reader.yqlQuery(my.rssTestUrl,rssResults); });
The rss2Objects
module also provides the ability to directly parse the RSS feed with XML. This option provides the best download performance for larger feeds.
To use the XML feed directly, simply call the query
method on the rss2Objects
module. The query
method takes three arguments:
channel.item
is provided. This tells the query
method to only return nodes from the channel item
element list. If you want all objects returned, simply pass a null value as an argument.xmlButton.addEventListener('click',function(e){ var queryPath = "channel.item"; my.reader.query(my.rssTestUrl,queryPath,rssResults); });
Both YQL and XML parsing demonstrations use the callback method shown next. This function takes the object dictionary provided by the rss2objects
module and creates TableView
rows for display:
function rssResults(e){
e
in this function provides the result returned from the rss2Objects
module. The first step is to check if the feed was returned successfully. This is done by checking the e.success
property, as the following code block shows:if(!e.success){ alert("Sorry we encountered an error"); tableView.setData([]); return; }; var items = e.rssDetails.items; var itemCount = items.length; var rows = [];
Ti.UI.TableViewRow
definition is built for each item:for (var iLoop=0;iLoop<itemCount ;iLoop++){ rows.push({ title: items[iLoop].title, article : items[iLoop], height: 60, hasChild:true, color:'#000' }); }
Ti.TableView
for display:tableView.setData(rows); };
The rss2objects
module provides a straightforward API for reading RSS feeds. The two primary methods provided by the rss2object.js
module are detailed in the following sections.
The
yqlQuery
method uses Titanium's built-in YQL provider to parse the provided RSS feed URL into a dictionary of objects:
exports.yqlQuery = function(url,callback){
onComplete
method is used as a callback to the Ti.Yahoo.yql
function. This method will process the YQL results into a standard format for consumption.function onComplete(e){
e
is a dictionary (with the results of the RSS feed query) provided by YQL.var results = { success:false, rssDetails : { url: url, full : null, items:null } };
e.success
property is checked to determine if the YQL statement generated an error. On Android, you must check the e.data
property for null
instead of using the e.success
property.//Determine if we have an error results.success = !((_isAndroid && e.data == null)||(!_isAndroid && (e.data == null || e.success==false)));
e.data.items
is added to the results.rssDetails.items
array that will later be the callback method:if(results.success){ results.rssDetails.items = []; var itemCount = e.data.item.length; for (var iLoop=0;iLoop<itemCount ;iLoop++){ results.rssDetails.items.push({ //Add each field in our items }); } }
callback
method, when calling the yqlQuery
module method:callback(results); };
var yQuery = 'SELECT title, link, description,'; yQuery += ' pubDate,guid,author,comments,'; yQuery += ' enclosure,source FROM rss WHERE url ='; yQuery += '"' + url + '"';
Ti.Yahoo.yql
method to run the query and send the results to the provided onComplete
callback function:Ti.Yahoo.yql(yQuery, onComplete); };
The q
uery
method uses Titanium's HTTPClient
and XML modules to read the provided RSS URL and to confirm the provided XML into a dictionary of objects:
exports.query = function(url,pathQuery,callback){ var workers = { results : { success:false, rssDetails : { url:url,full : null,items:null } },
whenComplete
function is invoked when the query
method has completed processing or resulted in an error. The whenComplete
method is used to wrap the callback
argument and provide the query results.whenComplete : function(){ callback(workers.results); } };
var xhr = Ti.Network.createHTTPClient();
onload
callback is created to retrieve the HTTP response provided by the RSS feed:xhr.onload = function(e) {
responseXML
property is used to gather the XML results from the RSS feed:var xml = this.responseXML;
var objResults = helpers.parseToObjects (xml);
null
, use the callback method to notify the user that the module failed to read the provided RSS feed:if(objResults ==null){ workers.whenComplete(); return; }
workers.results.rssDetails.full = objResults; workers.results.success = true; workers.results.rssDetails.items = objResults.item;
pathQuery
string was provided, run the query and update the results
object with the output from the queryByPath
method.if(pathQuery!=null){ workers.results.rssDetails.items = helpers.queryByPath(wobjResults,pathQuery); } };
onerror
callback to handle an error generated during the HTTPClient
request.xhr.onerror = function(e) { Ti.API.info(JSON.stringify(e)); workers.whenComplete(); };
GET
request to the RSS URL provided.xhr.open('GET', url); xhr.send(); };
18.189.178.53