Wednesday, April 13, 2011

Read twitter feeds using as3

if you ever tried to read twitter news directly using flash you will find that you will receive a security error cause flash have a sand box security which mean that twitter should add a cross domain file on their server.

in order to make work you need to create php file that load twitter news and send the result back to the flash as xml as below :

  • create new php file and name it twitter.php and then copy&paste below code :
<?php
/*Get Content from Twitter
*/

function get_content($url)
{
$ch = curl_init();

curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_HEADER, 0);

ob_start();

curl_exec ($ch);
curl_close ($ch);
$string = ob_get_contents();

ob_end_clean();

return $string;
}

#usage:
$content = get_content ("http://twitter.com/statuses/user_timeline.xml?screen_name=your twitter name");
echo $content;

  • now in your flash create new class name Twitter.as and this class can be called from anywhere in your flash and then parse the result xml

package 
{
   
    import flash.net.*;
    import flash.events.EventDispatcher;
    import flash.events.Event;
    import EventType.EventType;
    public class Twitter extends EventDispatcher 

{
       
        private static var instant = null ;
        private var twitterAddress:String = "twitter.php" ;
        public var xmlTweets:XML = null;
        public function Twitter()
        {
           
        }
        public static function GetInstant():Twitter
        {
            if(instant==null)
                instant = new Twitter();
            return instant;
        }
        public function GetLatestNews()
        {
           
            var twitterLoader:URLLoader = new URLLoader();
                twitterLoader.load(new URLRequest(twitterAddress));
                twitterLoader.addEventListener(Event.COMPLETE, ProcessTweets);

        }
        private function ProcessTweets(e:Event):void
        {
            xmlTweets = new XML(e.target.data);
            dispatchEvent(new Event("TweetsLoaded"));
        }

    }
   
}

  • the final step now is to call the twitter class from ur flash and retrieve the result:
var twitter:Twitter = Twitter.GetInstant();
            twitter.addEventListener("TweetsLoaded",TweetsLoaded);
            twitter.GetLatestNews();

 function TweetsLoaded(e:Event)
 {
var twitter:Twitter =  Twitter.GetInstant();
            xmlTweets = twitter.xmlTweets;      
}



Enjoy :)



No comments:

Post a Comment

Create facebook Iframe Application Using flash AS3 API ( Updated Version ).

please like and post your questions :  http://www.facebook.com/pages/FlashCS5-Tutorials/176320862386436 After I have received a lot of requ...