Consuming RSS feeds

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.

Consuming RSS feeds

Getting ready

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:

Getting ready

How to do it…

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"
};

Creating a UI for the sample app

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.

  1. First we create our Ti.UI.Window to attach all UI elements onto:
      var win = Ti.UI.createWindow({
        backgroundColor:'#fff'
      });
  2. Next, a button is created to demonstrate how to use YQL to load an RSS feed:
      var yqlButton = Ti.UI.createButton({
        title:"Load Using YQL",left:0 , width: 140, height:40, top:90
      });
      win.add(yqlButton);
  3. A button is then added to demonstrate how to load an RSS feed using XML Parsing:
      var xmlButton = Ti.UI.createButton({
        title:"Load Using XML",right:0 , width: 140,height:40, top:90
      });
      win.add(xmlButton);
  4. Finally, a 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);

Reading an RSS feed with YQL

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);
  });

Reading an RSS feed with XML parsing

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:

  • The URL for the RSS feed you wish to read.
  • An optional dot query syntax that allows you to provide the path of the nodes you want returned. In the next example, 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.
  • The third argument is the callback method where the module will send the results once processing has been completed.
    xmlButton.addEventListener('click',function(e){
      var queryPath = "channel.item";
      my.reader.query(my.rssTestUrl,queryPath,rssResults);
    });

Displaying the articles

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){
  1. The parameter 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 = [];
  2. Next, all of the RSS items are looped through and a 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'
          });
        }
  3. Finally, the article rows built in the previous step are added to the Ti.TableView for display:
        tableView.setData(rows);
      };

How it works…

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.

Using the yqlQuery function

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){
  1. The 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){
  2. The argument 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
          }
        };
  3. The 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)));
  4. If successful, the 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
            });
          }
        }
  5. The results of our YQL-parsed RSS feed are provided to the initially used callback method, when calling the yqlQuery module method:
        callback(results);
      };
  6. The following snippet demonstrates a YQL select query that will return a title, link, description, and other listed columns from the RSS feed (of the URL argument provided):
      var yQuery = 'SELECT title, link, description,';
        yQuery += ' pubDate,guid,author,comments,';
        yQuery += ' enclosure,source FROM rss WHERE url =';
        yQuery += '"' + url + '"';
  7. The next code block demonstrates using the Ti.Yahoo.yql method to run the query and send the results to the provided onComplete callback function:
      Ti.Yahoo.yql(yQuery, onComplete);
    };

Using the query function

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
      }
    },
  1. The 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);
        }
      };
  2. Action taken by this part of the recipe is to create an HTTP client:
      var xhr = Ti.Network.createHTTPClient();
  3. An onload callback is created to retrieve the HTTP response provided by the RSS feed:
      xhr.onload = function(e) {
  4. When the request is returned, the responseXML property is used to gather the XML results from the RSS feed:
        var xml = this.responseXML;
  5. The XML results are then converted to objects using our helper method:
        var objResults = helpers.parseToObjects (xml);
  6. If the converted XML object is 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;
        }
  7. If the XML was successfully able to be converted into objects, populate the query results with the full XML results and create a flag indicating the query was successfully executed.
        workers.results.rssDetails.full = objResults;
        workers.results.success = true;
        workers.results.rssDetails.items = objResults.item;
  8. If a 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);
        }
      };
  9. Provide an onerror callback to handle an error generated during the HTTPClient request.
      xhr.onerror = function(e) {
        Ti.API.info(JSON.stringify(e));
        workers.whenComplete();
      };
  10. Open the HTTP client and send a GET request to the RSS URL provided.
      xhr.open('GET', url);
      xhr.send();
    };

    Tip

    The order in which the functions are called is important. The open method must be called before calling the send method, as shown in the previous code section.

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.180.81