Flash AS3 Search Twitter API

At some point in your Flash career you will be asked to implement some sort of Flash widget that communicates with the latest social community apps, like Facebook and Twitter. This post was influenced by a clients request for an application that would display Twitter feeds based on a particular search term . The following example is a proof of concept based off the clients inquiry.

Press the Search button to display the tweet results. You can use a variety of search operators in your query. For a list of available operators check out http://search.twitter.com/operators


NOTE** Due to Twitter limitations on the amount of queries a user can make in an hour, this may not be the best solution for high traffic websites. There are alternative approaches, which maybe the subject of an upcoming post.

Thanks to the open source Flash community and the Twitter API, there are a few existing Twitter Flash API libraries we can choose from. The following is a list of current libraries you can find on the world wide web:

  • TwitterScript by Michael Galpin. AS3 API, originally from Twitter, now open sourced.
  • SWX Twitter API by Aral Balkan.
  • Tweetr by Sandro Duccesschi. AS3, supports the REST API, Search API, and URL shortening.
  • Coderanger by Dan Petitt. Flex/Air OAuth library class.
  • What can these Twitter Libraries do? For the most part they can:

  • authenticate a user
  • set authenticated user’s status
  • set authenticated user’s mobile notifications on/off
  • return a list of friends and their statuses
  • return a public user or a friend of an authenticated user’s timeline
  • return authenticated user’s friends’ timeline
  • return public timeline
  • add list members
  • add list subscriptions
  • block users
  • return list members
  • For the example app, I decided to use theTweetr library. I choose the library based on the Flash Ide that I was developing on at the time, Flash CS3. I also wanted to dig into the libraries source code just in case I wanted to extend or revise it. The other resources used a Flash SWC or SWX. The flash example is pretty straight forward. I utilize the Flash UI components (Button, InputText) for the basic ui and I created a movieclip that is used to display the Twitter feed results.

    The following is the document class:

    /****************************
    * Manuel Gonzalez           *
    * design@stheory.com        *
    * www.stheory.com           *
    * www.codingcolor.com       *
    *****************************/

    package {
        import com.swfjunkie.tweetr.Tweetr;
        import com.swfjunkie.tweetr.events.TweetEvent;
        import com.swfjunkie.tweetr.data.DataParser;
        import com.utils.StringUtils;
        import flash.display.Sprite;
        import flash.events.Event;
        import flash.text.TextField;
        import flash.events.MouseEvent;
        import fl.controls.TextInput;
        import flash.display.MovieClip;

        public class Main extends Sprite {
           
            private var _twtr:Tweetr;
            private var _currentSearchKeyword:String="#earthday";
            private var _lang:String="en";
            private var _numTweets:Number = 10;
            private var _searchArray:Array;
            private var _content:Sprite;
            private var _panelsCreated:Boolean = false;
            private var _tnArray:Array;
            private var _searchButton:Button;
            private var _searchInput:TextInput;
            private var _circleAnimation:CircleAnimation;
           
            public function Main() {
               
                _content = new Sprite();
                _content.x = 20;
                _content.y = 65;
                addChild(_content);
                _searchButton = sButton;
                _searchInput = sInput;
                _searchInput.text = _currentSearchKeyword;
                _twtr = new Tweetr();
                addSearchFormListeners();
               
               
            }
            /*
            Method:addSearchFormListeners
            Parameters:
            Returns:
            */

            private function addSearchFormListeners():void {
                _searchButton.addEventListener(MouseEvent.CLICK, startTwitterSearch);
                _searchButton.enabled = true;
                _searchInput.addEventListener(Event.CHANGE,updateSearchKeywords);
                _searchInput.enabled = true;
            }
            /*
            Method:removeSearchFormListeners
            Parameters:
            Returns:
            */

            private function removeSearchFormListeners():void {
                _searchButton.removeEventListener(MouseEvent.CLICK, startTwitterSearch);
                _searchButton.enabled = false;
                _searchInput.removeEventListener(Event.CHANGE,updateSearchKeywords);
                _searchInput.enabled = false;
            }
            /*
            Method:addTweetrListeners
            Parameters:
            Returns:
            */

            private function addTweetrListeners():void
            {
                _twtr.addEventListener(TweetEvent.COMPLETE,onCompleteHandler);
                _twtr.addEventListener(TweetEvent.FAILED,onFailedHandler);
                _twtr.addEventListener(TweetEvent.STATUS,onStatusHandler);
               
            }
            /*
            Method:removeTweetrListeners
            Parameters:
            Returns:
            */

            private function removeTweetrListeners():void
            {
                _twtr.removeEventListener(TweetEvent.COMPLETE,onCompleteHandler);
                _twtr.removeEventListener(TweetEvent.FAILED,onFailedHandler);
                _twtr.removeEventListener(TweetEvent.STATUS,onStatusHandler);
               
            }
            /*
            Method:startTwitterSearch
            Parameters:
            event:MouseEvent
            Returns:
            */

            private function startTwitterSearch(event:MouseEvent):void {
                searchTwitter();
            }
            /*
            Method:searchTwitter
            Parameters:
            Returns:
            */

            private function searchTwitter():void
            {
                removeSearchFormListeners();
                addTweetrListeners();
                addLoadingAnimation();
                _twtr.search(_currentSearchKeyword,_lang,_numTweets);
            }
            /*
            Method: addLoadingAnimation
            Parameters:
            Returns:
            */

            private function addLoadingAnimation():void {
                _content.visible=false;
                _circleAnimation = new CircleAnimation();
                _circleAnimation.x = (resultBkg.x + resultBkg.width/2) - _circleAnimation.width/2;
                _circleAnimation.y = (resultBkg.y + resultBkg.height/2) - _circleAnimation.height/2;
                addChild(_circleAnimation);
            }
            /*
            Method: removeLoadingAnimation
            Parameters:
            Returns:
            */

            private function removeLoadingAnimation():void {
                removeChild(_circleAnimation);
                _content.visible=true;
            }
            /*
            Method: updateSearchKeywords
            Parameters:
            event:Event
            Returns:
            */

            private function updateSearchKeywords(event:Event):void {
                if (_searchInput.text !="") {
                    _currentSearchKeyword = _searchInput.text;
                }
            }
            /*
            Method: onCompleteHandler
            Parameters:
            event:TweetEvent
            Returns:
            */

            private function onCompleteHandler(event:TweetEvent):void
            {
                //trace("Complete " + event.data);
                var sXml:XML = new XML(event.data);
                _searchArray = DataParser.parseSearchResults(sXml);
                createTweetPanel(_searchArray);
                removeTweetrListeners();
                addSearchFormListeners();
                removeLoadingAnimation();
            }
            /*
            Method: onFailedHandler
            Parameters:
            event:TweetEvent
            Returns:
            */

            private function onFailedHandler(event:TweetEvent):void
            {
                //trace("Failed " + event);
            }
            /*
            Method: onStatusHandler
            Parameters:
            event:TweetEvent
            Returns:
            */

            private function onStatusHandler(event:TweetEvent):void
            {
                //trace("Status " + event.data);
            }
            /*
            Method: makeClickable
            Parameters:
            inStr:String
            Returns: String
            */

            private function makeClickable(inStr:String):String
            {
                var str:String = inStr;
                var hasLink:Boolean = false;
                var nstr:Array = str.split(' ');
                var len:int = nstr.length;
               
                for( var i:int = 0; i < len; i++ )
                {
                   
                    var n = (nstr[i]).indexOf("http://");
                    if( n > -1 ){
                         nstr[i] ="<font color=\"#0000dd\"><A HREF='"+ nstr[i]+ "' target='_blank'><U>"+ nstr[i]+"</U></A></font>";
                        hasLink = true;
                    }
                }
                if(hasLink){
                    return nstr.join(' ');
                }else{
                    return str;
                }
            }
            /*
            Method:createTweetPanel
            Parameters:
            inArray:Array
            Returns:
            */

            private function createTweetPanel(inArray:Array):void {
                if(_panelsCreated)
                {
                    var child:int = _content.numChildren;
                    while( child -- )
                    {
                        _content.removeChildAt(child);
                    }
                }
               
                _tnArray = new Array();
                var len:int = inArray.length;
                for (var i:uint = 0; i < len; i++) {
                    var tn:TweetPanel = new TweetPanel();
                    tn.uField.text = StringUtils.beforeFirst(inArray[i].user,"(");
                    tn.tField.htmlText =  makeClickable(inArray[i].text);
                    //the data objects
                    //trace(inArray[i].createdAt);
                    //trace(inArray[i].id);
                    //trace(inArray[i].link);
                    //trace(inArray[i].text);
                    //trace(inArray[i].user);
                    //trace(inArray[i].userLink);
                    //trace(inArray[i].userProfileImage);
                    _content.addChild(tn);
                    _tnArray.push(tn);
                }
                _panelsCreated = true;
                adjustLayout();
            }
            /*
            Method:adjustLayout
            Parameters:
            Returns:
            */

            private function adjustLayout():void {
                var tnHeight:Number;
                var tnLen:int = _tnArray.length
                for (var j:uint = 0; j < tnLen; j++) {
                    _tnArray[j].y = (_tnArray[j].y+ _tnArray[j].height)*j;
                    tnHeight = _tnArray[j].height;
                }
               
            }
       
       
       
       
        }
       
    }

    You will notice a few other things in the code that may be of some use to you, like the makeClickable() method. The method essentially takes a string splits it up into an array, looks for “http://” and rebuilds the string with an active link.
    Take the code and improve on it.
    Review the createTweetPanel() method to find trace statements that will assist you on including a userLink or userProfileImage, amongst other things.

    I would like to Thank Sandro Duccesschi for making his library available to the public.

    Enjoy!

    Download Source:
    Flash Twitter Search (57)

    Share:
    • Facebook
    • Google Bookmarks
    • Faves
    • Twitter
    • Yahoo! Bookmarks

    4 Responses to “Flash AS3 Search Twitter API”

    1. [...] Go here to read the rest: Flash AS3 Search Twitter API- Coding Color [...]

    2. Hi, Great post about Twitter. I think Twitter is going to be one of the best networks because of the fact that it is supported by so many industries. I also think when Twitter shows some of it’s new functions, returning traffic will increase to show the real growth of the network. Keep up the great work!

    3. Awesome blog post, thanks for keeping me busy! Twitter RULES!

    4. Johnny IPL says:

      Good afternoon, This is a superb blog, and Allow me to agree with what was composed here. I will be back to see the comments soon. Thanks

    Leave a Reply

    Coding Color | 2009 All Rights Reserved.