Home / Articles / Adobe Flash / Creating a Twitter Widget with Flash

Creating a Twitter Widget with Flash

Contents

  1. Designing the Flash Widget
  2. Writing the Twitter Widget Functionality

Article Description

With the help of ActionScript 3.0 and PHP, Kris Hadlock, author of Ajax for Web Application Developers, shows how easily you can add your tweets to your website.
Writing the Twitter Widget Functionality

Writing the Twitter Widget Functionality

Now that you have your widget designed, you can start writing code. Create a new ActionScript file called Tweeter.as and add it as the Document class in your Flash tweeter.fla file.

Tweeter.as has been added to the com.studiosedition package. Therefore, you'll need to save Tweeter.as into a corresponding folder structure; for example, com/studiosedition (see Figure 5).

Listing 1 shows the Tweeter.as file. We'll examine the code in detail after the listing.

Listing 1—Creating the Twitter widget (Tweeter.as).

package com.studiosedition
{
 import flash.display.*;
 import flash.events.*;
 import flash.net.*;
 import flash.text.*;
 
 public class Tweeter extends MovieClip
 {
  public function Tweeter()
  {
   var baseUrl:String = ""; //YOUR BASE URL
   var twitterFeed:String = "https://twitter.com/statuses/user_timeline/45266608.rss"; //YOUR TWITTER RSS URL
   var request:URLRequest = new URLRequest(baseUrl+"service/gateway.php?feed="+twitterFeed);
   
   var loader = new URLLoader();
   loader.addEventListener(Event.COMPLETE, onRSSLoaded);
   loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
   loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);
   loader.load(request);
  }
  
  private function onRSSLoaded(e:Event):void
  {
   var rss:XML = new XML( URLLoader(e.target).data );
   this.titleTxt.htmlText = '<a href="'+ rss.channel.link +'" target="_blank">'+ rss.channel.title +'</a>';
   
   var tweetContainer:MovieClip = new MovieClip();
   for each(var item:XML in rss..item)
   {
    var tweet:Tweet = new Tweet(item.description, item.guid);
    tweet.y = tweetContainer.height;
    tweetContainer.addChild(tweet);
   }
   tweetPane.source = tweetContainer;
  }
  
  private function onIOError(e:IOErrorEvent):void
  {
   trace("IOError : " + e.text);
  }
  
  private function onSecurityError(e:SecurityErrorEvent):void
  {
   trace("SecurityError : " + e.text);
  }
 }
 
}

Tweeter.as starts with the package name and then the imported packages we'll need to use. Since our Tweeter class is a Document class, we're extending MovieClip. For the sake of saving time, the Tweeter constructor immediately gets to business, defining the baseUrl and twitterFeed variables that will be used to construct the request to the Twitter feed. (Define your own website URL and Twitter feed here.) After the variables are defined, the baseUrl and twitterFeed variables are used to make a URLRequest through the gateway.php file that we'll create shortly. We're not making a direct call to the Twitter feed because, at the time I wrote this article, Twitter wasn't allowing remote access to the cross-domain policy due to a security threat.

With the URLRequest in place, we create a URLLoader instance, add a few event listeners to handle the response, and finally load the request. The event listeners that we added will handle one of three responses:

  • Success
  • I/O error
  • Security error

Since error handling can easily be a separate set of articles, I've only written simple callback functions for the I/O and security errors. When a successful response has been received, the onRSSLoaded method that we defined in the listener is triggered.

The onRSSLoaded method receives the event object, casts the event to a URLLoader to retrieve the data from the response, and finally casts the data to a new XML instance called rss. With our rss variable created, we can immediately start accessing nodes from the Twitter feed. The first nodes that we access are rss.channel.link and rss.channel.title, which we use to add a hyperlink to the titleTxt TextField that we designed at the start of this article for our header.

Functionality Behind the Twitter Messages

Now that we have the Twitter feed title, we need to think about how we'll add the tweets. Since we'll want to use the tweetPane instance to handle scroll functionality for our messages, we'll need to add all of our tweets to a container that will be assigned to the tweetPane. We'll create a tweetContainer MovieClip instance, so the items can be accessed from the feed and added to the tweetContainer. Each item will contain the individual tweet title, message, guid, and pubDate, but in this article we'll only be using the description and guid (as the hyperlink back to the original message on Twitter).

While looping through the rss..items, we'll start using the tweet MovieClip symbol that we added to our library to handle displaying the message in the widget. In order to use the tweet MovieClip, we must create a class for the tweet symbol, which handles the display of our messages (see Listing 2).

Listing 2—Handling how each Twitter message is displayed (Tweet.as).

package com.studiosedition
{
 import flash.display.*;
 import flash.text.*;
 
 public class Tweet extends MovieClip
 {
  public function Tweet(txt, link)
  {
   this.tweetTxt.autoSize = TextFieldAutoSize.CENTER;
   this.tweetTxt.htmlText = '<a href="'+ link +'" target="_blank">'+ txt +'</a>';
   this.tweetBg.height = this.tweetTxt.height+20;
  }
 }
 
}

The Tweet object will accept two arguments: a description and guid. Once that's created, we'll set the y position of the tweet in the tweetContainer based on the previous tweets and then add the new tweet to the tweetContainer. With all the tweets added to the tweetContainer, all we need to do to display the messages is set the tweetContainer as the source of the tweetPane.

Each of the Tweet instances that were created in Listing 1 need to be linked to the Tweet.as class in the library in order to function properly. Once linked, the Tweet class handles the display of each tweet message, including the resizing of the tweetTxt TextField, the creation of the message hyperlink, and the resizing of the tweetBg MovieClip that we designed earlier in the article.

Making a Remote Twitter Feed Request

As mentioned earlier, a remote request to Twitter was not possible at the time of writing this article, due to a security threat with public access to Twitter's cross-domain policy file. Therefore, a PHP file, gateway.php, has been created to bridge the gap between our Flash widget and the remote Twitter feed (see Listing 3). Simply pass a URL to gateway.php for any Twitter feed, and it will use the file_get_contents function to access the feed, writing the data directly as a response.

Listing 3—Bridging the gap between Flash and the Twitter RSS feed (gateway.php).

<?php
header("Content-Type: application/xml; charset=UTF-8");
$feed = (isset($_REQUEST['feed'])) ? $_REQUEST['feed'] : '';
if(!empty($feed) || is_string($feed)) echo file_get_contents($feed);
?>

This widget is just a starting point for accessing and parsing any kind of RSS feeds with ActionScript 3.0. Feel free to experiment and enhance my example.

Follow me on Twitter @khadlock.