Home » ActionScript 3.0, XML

Compare XML and Reload in AS3 + Twitter feed

20 July 2012 No Comment
Share on Facebook

In one of my Flash project i need to retrive twitter feed and update UI on new feed is available.

This is not a big task, any way below is the code might be useful for the beginners in AS3.

Task:

Compare XML and need to reload it and update UI if new XML is available.

Solution:

Checking the XML feed in Timer Event and load it and compare with old feed.

AS3 Code :

Entire Code For loading Twitter feed and Check for new Updates

var timer:Timer = new Timer(15000,1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, handleTimerComplete)
timer.start();

var userName:String = "coolmobilesites"
var currentXML:XML;
var oldXML:XML;

function handleTimerComplete(e:TimerEvent):void
{

	getXMLFeed(userName)
	timer.start();
}

var _apiURL:String = "http://api.twitter.com/1/statuses/user_timeline.xml?count=10&screen_name=";
getXMLFeed(userName)

function getXMLFeed(account:String):void
{
	trace("feed called");

	var url:String		= _apiURL+account+"&"+Math.random();
	var req:URLRequest	= new URLRequest(url);
	var loader:URLLoader	= new URLLoader(req);

	loader.addEventListener(IOErrorEvent.IO_ERROR, handleIOError);
	loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, handleSecurityError);
	loader.addEventListener(Event.COMPLETE, handleLoadComplete);

}

function handleIOError(e:Event):void{}
function handleSecurityError(e:Event):void{}

function handleLoadComplete(event:Event):void
{
	var data:XML	= new XML((event.target as URLLoader).data);

	if(currentXML == null )
	{
		currentXML = XML(event.target.data);
	}
	else
	{
		oldXML = currentXML;
		currentXML = XML(event.target.data);
		//If feed is different, update UI
		if( oldXML != currentXML ){

			//Do the UI or Application update here

		}
	}
}

Accessing Twitter Feed in AS3:

Below is the twitter api to access any twitter user timeline. Just try to open below URL in browser you will see the XML feed of “Coolmobilesites” feed.

http://api.twitter.com/1/statuses/user_timeline.xml?count=10&screen_name=coolmobilesites

Try to call the above feed URL in AS3 the same way how we call a external XML file.

Compare XML in AS3:

Here we are comparing the XML file loaded with the XML previously loaded by storing it in OldXML variable.

oldXML = currentXML;
	currentXML = XML(event.target.data);

	if( oldXML != currentXML ){

		//Do the UI or Application update here

	}

Conclusion:

Simple way of accessing twitter feed and compare XML for updates.

GET THE UPDATES VIA EMAIL

We don't share your email anywhere, grab our rss via feedburner