<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="http://feedproxy.google.com/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feedproxy.google.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>The Tech Labs » Webservices</title>
	
	<link>http://www.thetechlabs.com</link>
	<description>Adobe Air, Flash and Flex Tutorials</description>
	<pubDate>Thu, 23 Oct 2008 22:58:12 +0000</pubDate>
	<generator>http://wordpress.org/?v=abc</generator>
	<language>en</language>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feedproxy.google.com/TheTechLabs_webservices" type="application/rss+xml" /><item>
		<title>Creating a AIR Web Service Package with Flash and AS3- Base Service Class And Simple Twitter API</title>
		<link>http://feedproxy.google.com/~r/TheTechLabs_webservices/~3/9GmCJYhawBo/</link>
		<comments>http://www.thetechlabs.com/flash/creating-a-as3-web-service-package-base-service-class-and-simple-twitter-api/#comments</comments>
		<pubDate>Wed, 03 Sep 2008 22:18:47 +0000</pubDate>
		<dc:creator>Reynaldo Columna</dc:creator>
		
		<category><![CDATA[AIR]]></category>

		<category><![CDATA[Flash]]></category>

		<category><![CDATA[Latest]]></category>

		<category><![CDATA[Webservices]]></category>

		<category><![CDATA[adobe air]]></category>

		<category><![CDATA[adobe flash]]></category>

		<category><![CDATA[API]]></category>

		<category><![CDATA[as3]]></category>

		<category><![CDATA[how-to]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://www.thetechlabs.com/?p=99</guid>
		<description><![CDATA[<p>In this series of tutorials, you will learn the basics of architecting a simple but powerful Web Services Package. We&#8217;ll start off by creating a class which will be the base of all our services and then continue to create a very simple Twitter API.</p>
<small><em>posted in <a href="http://www.thetechlabs.com/category/air/">AIR</a> by Reynaldo Columna <a href="http://www.thetechlabs.com/flash/creating-a-as3-web-service-package-base-service-class-and-simple-twitter-api/#comments">Leave A Comment</a><br />&copy;2008 <a href="http://www.thetechlabs.com">The Tech Labs</a>. All Rights Reserved.</em></small>]]></description>
			<content:encoded><![CDATA[<p>In this series of tutorials, you will learn the basics of architecting a simple but powerful Web Services Package. We&#8217;ll start off by creating a class which will be the base of all our services and then continue to create a very simple Twitter API.<em><strong></strong></em></p>
<p><em><strong>Please note that due to changes in the Twitter cross domain policy, the API we will create in this tutorial will not work online, but works perfectly in an AIR application.</strong></em></p>
<h3>Requirements</h3>
<p><strong>Adobe Flash CS3</strong></p>
<p><a title="Try / buy" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://www.adobe.com/products/flash/');" href="http://www.adobe.com/products/flash/" onclick="javascript:pageTracker._trackPageview('oclicks/http://www.adobe.com/products/flash/');" target="_blank">Try / Buy</a></p>
<p><strong>Adobe Intergrated Runtime (AIR) for Flash CS3</strong></p>
<p><a title="Download AIR for Flash CS3" href="http://www.adobe.com/products/air/develop/flash/" onclick="javascript:pageTracker._trackPageview('oclicks/http://www.adobe.com/products/air/develop/flash/');" target="_blank">Download</a></p>
<p><strong>Source Files</strong></p>
<p><a title="Download Source Files" onclick="javascript:pageTracker._trackPageview('/downloads/tutorials/files/flash/fcarrera/flickrsearchengine/flickrsearchengine_sfiles.zip');" href="http://thetechlabs.com/tutorials/files/flash/Reynaldo/Webservice/AIR Webservice Tutorial.zip" onclick="javascript:pageTracker._trackPageview('downloads/tutorials/files/flash/Reynaldo/Webservice/AIR Webservice Tutorial.zip');" target="_self">Download</a></p>
<h3>Pre-Requesites</h3>
<p>Some experience in creating classes in AS3, if you dont know how to, don&#8217;t worry, you&#8217;ll learn here <img src='http://www.thetechlabs.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<h3>Create the package</h3>
<p>The first thing we need to do before actually coding anything is to create our class package. Creating a class package is very simple, we&#8217;ll create it right on our desktop. All you have to do is create a folder and name it &#8220;com&#8221;, that will be the main package. inthe &#8220;com&#8221; folder, create another folder identifying the name of your webservices collection, I&#8217;ll call mine &#8220;reyco1&#8243;. now in the &#8220;reyco1&#8243; folder create another folder called &#8220;webservices&#8221;. That&#8217;s it! package creation complete. Now how easy was that? Very!</p>
<p>Now create create an Actionscript file, name it &#8220;WebService.as&#8221; and save it in the &#8220;webservices&#8221; folder. This is the class that all our apis, such as Twitter API will use to connect to their respective web services. Crack that puppy open and lets get to the coding goodness!</p>
<h3>Coding the main WebService class</h3>
<p>All AS3 classes are contained within a package. We already created our package in the first step, basically a few nested folders. So we&#8217;ll start our class as so:</p>
<pre>package com.reyco1.webservice
{

}</pre>
<p>Now we need to import the classes that we need from flash in order to make our class work:</p>
<pre>package com.reyco1.webservice
{
	import flash.events.*;
	import flash.net.*;
}</pre>
<p>Our class will extend the &#8220;EventDispatcher&#8221; class which means that we will be able to dispatch much needed events. It will have additional properties and methods which we will include in later steps. In the meantime your class should look like this:</p>
<pre>package com.reyco1.webservice
{
	import flash.events.*;
	import flash.net.*;

	public class WebService extends EventDispatcher
	{

    }

}</pre>
<p>Now we create the variables that we will need in order to connect to the online web services. We&#8217;ll need a URLRequest, a URLLoader and a URLVariables along with a generic data variable that will hold information returned from the web service. We want to make this data variable public so that it can be accessed from outside the class:</p>
<pre>package com.helix.webservice
{
	import flash.events.*;
	import flash.net.*;

	public class WebService extends EventDispatcher
	{

		private var request:URLRequest;
		private var loader:URLLoader;
		private var variables:URLVariables;
		public var data:*

    }

}</pre>
<p>Now that we have all the variables we need, we can go ahead and create our constructor. The class constructor is a special method always named the same name as the class. Constructors can accept arguments or not. Our&#8217;s will accept one, an HTTP Request (I&#8217;ll explain in a bit). We&#8217;ll call the EventDispatcher constructor by calling the &#8220;super&#8221; method and then set our request variable to accept the HTTP Request:</p>
<pre>package com.reyco1.webservice
{
	import flash.events.*;
	import flash.net.*;

	public class WebService extends EventDispatcher
	{

		private var request:URLRequest;
		private var loader:URLLoader;
		private var variables:URLVariables;
		public var data:*

		public function WebService($servicePath:String)
		{
        	super();
			request = new URLRequest($servicePath);
		}
    }
}</pre>
<p>Now we&#8217;ll create our one and only method. This is the method that will make the call to the webservice. Our method will accept 2 arguments: the first is a &#8220;method&#8221; (String); we can set this method to be either &#8220;POST&#8221; or &#8220;GET&#8221;, ours will default to &#8220;POST&#8221;. Usually web services will tell you which method to use in order to access their information. The second argument is &#8220;arguments&#8221; (Object); This will hold any parameters that you would need to make your service call. Again, web services will tell you if you need to send any additional information with your call, ours defaults to null.</p>
<pre>package com.reyco1.webservice
{
	import flash.events.*;
	import flash.net.*;

	public class WebService extends DispatchExtension
	{

		private var request:URLRequest;
		private var loader:URLLoader;
		private var variables:URLVariables;
		public var data:*

		public function WebService($servicePath:String)
		{
			request = new URLRequest($servicePath);
		}

		/**
		 * Makes the web service call
		 * @param $method either POST or GET. POST is set as default
		 * @param $arguments any parameters or variables that you need to make with your web service call
		 *
		 */
		public function call($method:String="POST", $arguments:Object=null):void
		{
			variables = new URLVariables();
			if($arguments != null){
				for (var i:* in $arguments){
					variables[i] = $arguments[i];
				}
				request.data = variables;
			}
			request.method = $method.toUpperCase();
			loader = new URLLoader(request);
			loader.addEventListener(Event.COMPLETE, handleRequestLoaded);
			loader.addEventListener(IOErrorEvent.IO_ERROR, handleRequestError);
			loader.load(request);
		}
    }
}</pre>
<p>Now let me explain what&#8217;s going on up there. Basically we set up our URLVariables by recursing through the &#8220;$arguments&#8221; parameter if it&#8217;s not set to null and set it to the &#8220;data&#8221; proerty or our URLRequest. Then we specify the call method by setting the URLRequest&#8217;s &#8220;method&#8221; property to the &#8220;$method&#8221; parameter. We then continue to set up out URLLoader instance by adding the COMPLETE and IOErrorEvent event listeners. Finally we make the service call by executing the URLLoader&#8217;s call method and passing it the URLRequest.</p>
<p>Now we create the handlers for our event listeners:</p>
<pre>package com.reyco1.webservice
{
	import flash.events.*;
	import flash.net.*;

	public class WebService extends EventDispatcher
	{

		private var request:URLRequest;
		private var loader:URLLoader;
		private var variables:URLVariables;
		public var data:*

		public function WebService($servicePath:String)
		{
			request = new URLRequest($servicePath);
		}

		/**
		 * Makes the web service call
		 * @param $method either POST or GET. POST is set as default
		 * @param $arguments any parameters or variables that you need to make with your web service call
		 *
		 */
		public function call($method:String="POST", $arguments:Object=null):void
		{
			variables = new URLVariables();
			if($arguments != null){
				for (var i:* in $arguments){
					variables[i] = $arguments[i];
				}
				request.data = variables;
			}
			request.method = $method.toUpperCase();
			loader = new URLLoader(request);
			loader.addEventListener(Event.COMPLETE, handleRequestLoaded);
			loader.addEventListener(IOErrorEvent.IO_ERROR, handleRequestError);
			loader.load(request);
		}

		private function handleRequestLoaded($event:Event):void
		{
			data = $event.target.data;
			this.dispatchEvent(new Event(&#8221;RESULT&#8221;, false));
		}

		private function handleRequestError($event:IOErrorEvent):void
		{
			data = {};
			this.dispatchEvent(new Event(&#8221;FAULT&#8221;, false));
		}

	}
}</pre>
<p>In the handlers, if the call is successfull, it sets the data variable to the data that the web service returns and fires a &#8220;RESULT&#8221; event. If the call is unsuccessful, set the data to an empty object and fires teh &#8220;FAULT&#8221; event. Now we&#8217;ll add getter and setter functions so that we may be able to dynamically set the web service path whenever we want.</p>
<pre>package com.reyco1.webservice
{
	import flash.events.*;
	import flash.net.*;

	public class WebService extends EventDispatcher
	{

		private var request:URLRequest;
		private var loader:URLLoader;
		private var variables:URLVariables;
		public var data:*

		public function WebService($servicePath:String)
		{
			request = new URLRequest($servicePath);
		}

		/**
		 * Makes the web service call
		 * @param $method either POST or GET. POST is set as default
		 * @param $arguments any parameters or variables that you need to make with your web service call
		 *
		 */
		public function call($method:String="POST", $arguments:Object=null):void
		{
			variables = new URLVariables();
			if($arguments != null){
				for (var i:* in $arguments){
					variables[i] = $arguments[i];
				}
				request.data = variables;
			}
			request.method = $method.toUpperCase();
			loader = new URLLoader(request);
			loader.addEventListener(Event.COMPLETE, handleRequestLoaded);
			loader.addEventListener(IOErrorEvent.IO_ERROR, handleRequestError);
			loader.load(request);
		}

		private function handleRequestLoaded($event:Event):void
		{
			data = $event.target.data;
			this.dispatchEvent(new Event(&#8221;RESULT&#8221;, false));
		}

		private function handleRequestError($event:IOErrorEvent):void
		{
			data = {};
			this.dispatchEvent(new Event(&#8221;FAULT&#8221;, false));
		}

		public function set servicePath($path:String):void
		{
			request = new URLRequest($path);
		}

		public function get servicePath():String
		{
			return request.url;
		}

	}
}</pre>
<p>That&#8217;s basically all we need for our base WebService calss! Was it easy? Hope so <img src='http://www.thetechlabs.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> lets fire it up by using it in a simple Twitter API!</p>
<h3>Using the newly created WebService class to make a simple Twitter API</h3>
<p>Create a new Actionscript file, name it &#8220;Twitter&#8221; and save it to the webservices folder. We want this class to fire events also, so lets start off by extending the EventDispatcher class. Remember also to import the flash events package and our WebService class too:</p>
<pre>package com.reyco1.webservice
{
	import com.reyco1.webservice.WebService;
	import flash.events.*;

	public class Twitter extends EventDispatcher
	{
    }

}</pre>
<p>Cool, let&#8217;s create a static private var that will hold an HTTP Status method provided by the online Twitter API. You can find all the Twiiter methods over at the Twitter RESR API Docunebtation here: http://apiwiki.twitter.com/REST+API+Documentation#HTTPStatusCodes. We&#8217;re going to use only one for now. The call to get all the Tweets on the public timeline.</p>
<p>We&#8217;re also going to need a private variable to represent our WebService class and a public array variable which will hold the parsed xml returned byt Twitter:</p>
<pre>package com.reyco1.webservice
{
	import com.reyco1.webservice.WebService;
	import flash.events.*;

	public class Twitter extends EventDispatcher
	{

		private static var PUBLIC_TIMELINE:String = "http://twitter.com/statuses/public_timeline.xml";

		private var twitterService:WebService;
		public var result:Array;

        }
    }
}</pre>
<p>Ok, now let&#8217;s set up our constructor. In the constructor we will set up our instance of the WebService class. Remeber that the WebService class needs to accept a service path in it&#8217;s constructor, so we&#8217;ll pass it our PUBLIC_TIMELINE path as default. We also set the result array to an empty array;</p>
<pre>package com.reyco1.webservice
{
	import com.reyco1.webservice.WebService;
	import flash.events.*;

	public class Twitter extends EventDispatcher
	{

		private static var PUBLIC_TIMELINE:String = "http://twitter.com/statuses/public_timeline.xml";

		private var twitterService:WebService;
		public var result:Array;

		public function Twitter()
		{
			twitterService = new WebService(Twitter.PUBLIC_TIMELINE);
			twitterService.addEventListener("RESULT", handleResult);
			twitterService.addEventListener("FAULT", handleFault);

			result = [];
		}
    }
}</pre>
<p>before we set up the handlers for the events fired from the WebService class, let&#8217;s create the method which will make the request for the public timeline to Twitter:</p>
<pre>package com.reyco1.webservice
{
	import com.reyco1.webservice.WebService;
	import flash.events.*;

	public class Twitter extends EventDispatcher
	{

		private static var PUBLIC_TIMELINE:String = "http://twitter.com/statuses/public_timeline.xml";

		private var twitterService:WebService;
		public var result:Array;

		public function Twitter()
		{
			twitterService = new WebService(Twitter.PUBLIC_TIMELINE);
			twitterService.addEventListener("RESULT", handleResult);
			twitterService.addEventListener("FAULT", handleFault);

			result = [];
		}

		public function requestPublicTimeline():void
		{
			twitterService.servicePath = Twitter.PUBLIC_TIMELINE;
			twitterService.call();
		}
    }
}</pre>
<p>What we&#8217;re doing is dynamically setting the service path on the Webservices class. Now, you may be asking yourself, &#8220;didn&#8217;t we just add that path up in the constructor?&#8221;, the answer is, yes. Never the less, it is good practice for us to set it up here again, basically because later on when we add new methods, we&#8217;ll have to set it to the new service path anyway, so might as well get used to it from now <img src='http://www.thetechlabs.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Afther the path is set, then we then execute the call method of our WebService class. Nothig is going to happen unless we add our event handlers, so let&#8217;s get to it!</p>
<pre>package com.reyco1.webservice
{
	import com.reyco1.webservice.WebService;
	import flash.events.*;

	public class Twitter extends EventDispatcher
	{

		private static var PUBLIC_TIMELINE:String = "http://twitter.com/statuses/public_timeline.xml";

		private var twitterService:WebService;
		public var result:Array;

		public function Twitter()
		{
			twitterService = new WebService(Twitter.PUBLIC_TIMELINE);
			twitterService.addEventListener("RESULT", handleResult);
			twitterService.addEventListener("FAULT", handleFault);

			result = [];
		}

		public function requestPublicTimeline():void
		{
			twitterService.servicePath = Twitter.PUBLIC_TIMELINE;
			twitterService.call();
		}

		private function handleFault($event:Event):void
		{
			result = [];
			this.dispatchEvent(new Event(&#8221;FAULT&#8221;));
		}

		private function handleResult($event:Event):void
		{
			var myResult:XML = new XML(twitterService.data);
			result = parseResult(myResult);
			this.dispatchEvent(new Event(&#8221;RESULT&#8221;));
		}
    }
}</pre>
<p>Nothing too fancy in the fault event handler. Basically, all it does is is just set the reult array to an ampty array and fires a new Fault event. Now, the good stuff is in the result event handler. The response we get from Twitter will be a String in an XML format, so once it arrives, we need make sure flash reads it as XML. Once that is done, we pass it to a method named &#8220;parseResult&#8221; which we will be seeing in the next step. Essentially, all the &#8220;parseResult&#8221; method does is take the xml returned from Twitter and parse it into an array of objects, better known as a &#8220;Collection&#8221;. Once the XML is parsed, it is set as the &#8220;result&#8221; array and a &#8220;RESULT&#8221; event is fired. Let&#8217;s see that crazy &#8220;parseResult&#8221; method:</p>
<pre>package com.reyco1.webservice
{
	import com.reyco1.webservice.WebService;
	import flash.events.*;

	public class Twitter extends EventDispatcher
	{

		private static var PUBLIC_TIMELINE:String = "http://twitter.com/statuses/public_timeline.xml";

		private var twitterService:WebService;
		public var result:Array;

		public function Twitter()
		{
			twitterService = new WebService(Twitter.PUBLIC_TIMELINE);
			twitterService.addEventListener("RESULT", handleResult);
			twitterService.addEventListener("FAULT", handleFault);

			result = [];
		}

		public function requestPublicTimeline():void
		{
			twitterService.servicePath = Twitter.PUBLIC_TIMELINE;
			twitterService.call();
		}

		private function handleResult($event:Event):void
		{
			var myResult:XML = new XML(twitterService.data);
			result = parseResult(myResult);
			this.dispatchEvent(new Event(&#8221;RESULT&#8221;));
		}

		private function handleFault($event:Event):void
		{
			result = [];
			this.dispatchEvent(new Event(&#8221;FAULT&#8221;));
		}

		private function parseResult($result:XML):Array
		{
			var objectArray:Array = [];
			var xml:XML = $result
			var xmllist:XMLList = xml.children();

			for(var a:Number = 0; a &lt; xmllist.length(); a++){
				var object:Object = {};
				for(var b:Number = 0; b&lt; xmllist[a].children().length(); b++){
					var item:XML = xmllist[a].children()[b];
					if(item.localName().toString() == &#8220;user&#8221;){
						var userObject:Object = {};
						for(var c:Number = 0; c &lt; item.children().length(); c++){
							userObject[item.children()[c].localName().toString()] = item.children()[c].toString()
						}
						object[item.localName()] = userObject;
					}else{
						object[item.localName()] = item.toString();
					}
				}
				objectArray.push(object);
			}
			return objectArray;
		}
	}
}</pre>
<p>With the &#8220;parseResult&#8221; method, each node in the XML will be parsed into an object containing the following values:</p>
<pre>id
in_reply_to_status_id
source
created_at
user
  -- name
  -- url
  -- screen_name
  -- description
  -- followers_count
  -- id
  -- protected
  -- profile_image_url
  -- location
in_reply_to_user_id
text
favorited
truncated</pre>
<p>I think it&#8217;s time we test ride this puppy! Let&#8217;s get to it!</p>
<h3>Creating a Twitter Application with our newly created Twitter API</h3>
<p>Crack open an fla file and set the stage dimensions to 310 by 400. We&#8217;ll start off by creating a container for each Tweet. The container movieclip will hold the users profile image and a textfield to display the user&#8217;s tweet. Each of a users profile image is 48 x 48, so create a square on the stage 48 x 48 and create a static text field which says &#8220;LOADING&#8221; and place it right at the center of the box. Now convert the whole thing into a MovieClip and instance name it &#8220;imageContainer&#8221;;</p>
<p><img class="alignnone size-full wp-image-101" title="image001" src="http://www.thetechlabs.com/wp-content/uploads/2008/09/image001.png" alt="" width="141" height="119" /></p>
<p><img src="images/image001.png" border="0" alt="" /></p>
<p>Now create a dynamic text field with the following properties:</p>
<p><img class="alignnone size-full wp-image-103" title="image002" src="http://www.thetechlabs.com/wp-content/uploads/2008/09/image002.png" alt="" width="500" height="89" /></p>
<p><img src="images/image002.png" border="0" alt="" /></p>
<p>Set the text field right next to the imageContainer and create a MovieClip out of the whole thing. So essentially at this point you should have ONE MovieClip on the stage. This movie clip should contain an 48 x 48 MovieClip instance named &#8220;imageContainer&#8221; and a dynamic text field instance named &#8220;twitTxt&#8221;</p>
<p><img class="alignnone size-full wp-image-104" title="image003" src="http://www.thetechlabs.com/wp-content/uploads/2008/09/image003.png" alt="" width="372" height="101" /></p>
<p><img src="images/image003.png" border="0" alt="" /></p>
<p>Drag another 5 instances of the newly created movie clip from the library and drop them on the stage and align them one under the other like shown below and instance name then item0, item1, item2, item3, item4 and item5:</p>
<p><img class="alignnone size-full wp-image-102" title="image004" src="http://www.thetechlabs.com/wp-content/uploads/2008/09/image004.png" alt="" width="297" height="310" /></p>
<p><img src="images/image004.png" border="0" alt="" /></p>
<p>That&#8217;s it for the timeline stuff. Select the first frame and open up your actions panel. The first thing we need to do is import our Twitter class;</p>
<pre>import com.reyco1.webservice.Twitter</pre>
<p>Now we create an instance of our Twitter API and have it listen to the &#8220;RESULT&#8221; event:</p>
<pre>import com.reyco1.webservice.Twitter

var twitter:Twitter = new Twitter();
twitter.addEventListener("RESULT", handleResult);</pre>
<p>Let&#8217;s set up the handler for the result event. In the handler we pass the first 6 of the objects in the result array to a &#8220;populateItem&#8221; method along with its index. Let&#8217;s take a look at the event handler and then we&#8217;ll see what that &#8220;populateItem&#8221; method looks like.</p>
<pre>import com.reyco1.webservice.Twitter

var twitter:Twitter = new Twitter();
twitter.addEventListener("RESULT", handleResult);

function handleResult($event:Event):void
{
	var result:Array = twitter.result;
	for(var a:Number = 0; a &lt; 6; a++){
		populateItem(a, result[a]);
	}
}</pre>
<p>Below we&#8217;ve added the &#8220;populateItem&#8221; method. Basically, this method adds the tweet to the text field in the item on stage along with adding the image to it&#8217;s imageContainer.</p>
<pre>import com.reyco1.webservice.Twitter

var twitter:Twitter = new Twitter();
twitter.addEventListener("RESULT", handleResult);

function handleResult($event:Event):void
{
	var result:Array = twitter.result;
	for(var a:Number = 0; a &lt; 6; a++){
		populateItem(a, result[a]);
	}
}

function populateItem($itemIndex:Number, $twitObject:Object):void
{
	this["item"+$itemIndex].twitText.text = $twitObject.text;
	var imageLoader:Loader = new Loader();
	this["item"+$itemIndex].imageContainer.addChild(imageLoader);
	var imagePath:URLRequest = new URLRequest($twitObject.user.profile_image_url);
	imageLoader.load(imagePath);
}</pre>
<p>Now all we have to do is call the &#8220;requestPublicTimeline&#8221; method of our Twitter API and we&#8217;re DONE!!</p>
<pre>import com.reyco1.webservice.Twitter

var twitter:Twitter = new Twitter();
twitter.addEventListener("RESULT", handleResult);

function handleResult($event:Event):void
{
	var result:Array = twitter.result;
	for(var a:Number = 0; a &lt; 6; a++){
		populateItem(a, result[a]);
	}
}

function populateItem($itemIndex:Number, $twitObject:Object):void
{
	this["item"+$itemIndex].twitText.text = $twitObject.text;
	var imageLoader:Loader = new Loader();
	this["item"+$itemIndex].imageContainer.addChild(imageLoader);
	var imagePath:URLRequest = new URLRequest($twitObject.user.profile_image_url);
	imageLoader.load(imagePath);
}

twitter.requestPublicTimeline();</pre>
<h3>Publishing your file as an AIR application</h3>
<p>Publishing a flash file as an AIR application cannot be any easier:</p>
<ul>
<li>Download the runtime installation file.</li>
<li>Double-click the runtime installation file.</li>
<li>In the installation window, follow the prompts to complete the installation.</li>
</ul>
<p>Once installed, follow these steps:</p>
<ul>
<li>Open your Flash FLA file.</li>
<li>If you’re opening a new Flash File (ActionScript 3.0), save it. If you don’t save it, a warning appears when you do the next step.</li>
<li>Select Commands &gt; AIR - Application And Installer Settings. An alert box appears, asking if you want to convert the file to Adobe AIR publish settings.</li>
<li>Click OK to convert the FLA file to Adobe AIR publish settings. The AIR - Application And Installer Settings dialog box appears.</li>
</ul>
<p>Simply publish your and all should work! I hope you have enjoyed this article and have been able to learn lots of stuff! In the next few tutorials, I&#8217;ll be adding more complex methods to our Twitter API and Hopefully at the end of the series, we&#8217;ll have a fully working Twitter Application!</p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" onmouseover="a2a_show_dropdown(this)" onmouseout="a2a_onMouseOut_delay()" href="http://www.addtoany.com/share_save?sitename=The%20Tech%20Labs&amp;siteurl=http%3A%2F%2Fwww.thetechlabs.com%2F&amp;linkname=Creating%20a%20AIR%20Web%20Service%20Package%20with%20Flash%20and%20AS3-%20Base%20Service%20Class%20And%20Simple%20Twitter%20API&amp;linkurl=http%3A%2F%2Fwww.thetechlabs.com%2Fflash%2Fcreating-a-as3-web-service-package-base-service-class-and-simple-twitter-api%2F" onclick="javascript:pageTracker._trackPageview('oclicks/http://www.addtoany.com/share_save?sitename=The%20Tech%20Labs&amp;siteurl=http%3A%2F%2Fwww.thetechlabs.com%2F&amp;linkname=Creating%20a%20AIR%20Web%20Service%20Package%20with%20Flash%20and%20AS3-%20Base%20Service%20Class%20And%20Simple%20Twitter%20API&amp;linkurl=http%3A%2F%2Fwww.thetechlabs.com%2Fflash%2Fcreating-a-as3-web-service-package-base-service-class-and-simple-twitter-api%2F');"><img src="http://www.thetechlabs.com/wp-content/plugins/add-to-any/share_save_171_16.gif" width="171" height="16" alt="Share/Save/Bookmark"/></a>

	</p><img src="http://feedproxy.google.com/~r/TheTechLabs_webservices/~4/9GmCJYhawBo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.thetechlabs.com/flash/creating-a-as3-web-service-package-base-service-class-and-simple-twitter-api/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.thetechlabs.com/flash/creating-a-as3-web-service-package-base-service-class-and-simple-twitter-api/</feedburner:origLink></item>
		<item>
		<title>Creating a Weather Widget with XML and AS3</title>
		<link>http://feedproxy.google.com/~r/TheTechLabs_webservices/~3/pxYdTWz7MLg/</link>
		<comments>http://www.thetechlabs.com/xml/creating-a-weather-widget-with-xml-and-as3/#comments</comments>
		<pubDate>Tue, 15 Jul 2008 23:15:24 +0000</pubDate>
		<dc:creator>Fausto Carrera</dc:creator>
		
		<category><![CDATA[Flash]]></category>

		<category><![CDATA[Webservices]]></category>

		<category><![CDATA[XML]]></category>

		<category><![CDATA[adobe flash]]></category>

		<category><![CDATA[API]]></category>

		<category><![CDATA[as3]]></category>

		<category><![CDATA[how-to]]></category>

		<category><![CDATA[tutorial]]></category>

		<category><![CDATA[weather service]]></category>

		<guid isPermaLink="false">http://www.thetechlabs.com/?p=80</guid>
		<description><![CDATA[<p>In this tutorial I&#8217;m presenting you a little weather widget, that could come handy for travel websites, or our personal page. If you make some changes on the code, you could show a different interface on your website, according to the weather on your city. Pretty cool stuff. We gonna connect weather.com XML data file with our flash widget. Weather.com offers us a free service to do that.</p>
<small><em>posted in <a href="http://www.thetechlabs.com/category/flash/">Flash</a> by Fausto Carrera <a href="http://www.thetechlabs.com/xml/creating-a-weather-widget-with-xml-and-as3/#comments">Leave A Comment</a><br />&copy;2008 <a href="http://www.thetechlabs.com">The Tech Labs</a>. All Rights Reserved.</em></small>]]></description>
			<content:encoded><![CDATA[<p>In this tutorial I&#8217;m presenting you a little weather widget, that could come handy for travel websites, or our personal page. If you make some changes on the code, you could show a different interface on your website, according to the weather on your city. Pretty cool stuff. We gonna connect weather.com XML data file with our flash widget. Weather.com offers us a free service to do that.</p>
<h3>Requirements</h3>
<p><strong>Adobe Flash CS3</strong></p>
<p><a title="Try / buy" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://www.adobe.com/products/flash/');" href="http://www.adobe.com/products/flash/" onclick="javascript:pageTracker._trackPageview('oclicks/http://www.adobe.com/products/flash/');" target="_blank">Try / Buy</a></p>
<p><strong>Source Files</strong></p>
<p><a title="Download Source Files" onclick="javascript:pageTracker._trackPageview('/downloads/tutorials/files/flash/fcarrera/flickrsearchengine/flickrsearchengine_sfiles.zip');" href="http://thetechlabs.com/tutorials/files/flash/fcarrera/weather/tutorial_weather_ xml_as3.rar"  target="_self">Download</a></p>
<h3>Sign up to weather.com</h3>
<p>The first thing we gonna do is login in our weather.com account:</p>
<p><a href="https://registration.weather.com/ursa/profile" onclick="javascript:pageTracker._trackPageview('oclicks/https://registration.weather.com/ursa/profile');">https://registration.weather.com/ursa/profile</a></p>
<p><img class="alignnone size-full wp-image-70" title="001" src="http://www.thetechlabs.com/wp-content/uploads/2008/07/001.png" alt="" width="499" height="193" /></p>
<p>Or if we already don&#8217;t have an account we could register for free in here:</p>
<p><a href="https://registration.weather.com/ursa/profile/new?" onclick="javascript:pageTracker._trackPageview('oclicks/https://registration.weather.com/ursa/profile/new?');">https://registration.weather.com/ursa/profile/new?</a></p>
<p><img class="alignnone size-full wp-image-71" title="002" src="http://www.thetechlabs.com/wp-content/uploads/2008/07/002.png" alt="" width="500" height="309" /></p>
<h3>Registering for weather.com XML Data Feed</h3>
<p>Once we are in our account, we gonna have a page like this one, where on the left we gonna have all the services we are subscribed<br />
and on the right, all the available services, the XML data feed is not there, it&#8217;s a little bit tricky.</p>
<p><img class="alignnone size-full wp-image-72" title="003" src="http://www.thetechlabs.com/wp-content/uploads/2008/07/003.png" alt="" width="500" height="355" /></p>
<p>So, we gonna signup to the XML data feed on this page</p>
<p><a href="https://registration.weather.com/ursa/xmloap/" onclick="javascript:pageTracker._trackPageview('oclicks/https://registration.weather.com/ursa/xmloap/');">https://registration.weather.com/ursa/xmloap/</a></p>
<p>Where we gonna tell to weather.com in which way we gonna use the data. If it&#8217;s for personal purpose, there&#8217;s no problem, but<br />
if it&#8217;s commercial purpose, you have to contact them, but everything is better explained on the mail you are going to receive.</p>
<p><img class="alignnone size-full wp-image-73" title="004" src="http://www.thetechlabs.com/wp-content/uploads/2008/07/004.png" alt="" width="500" height="436" /></p>
<p>So if our registration it&#8217;s oki, we gonna receive an email like this one (check on the spam inbox too, just in case).</p>
<p><img class="alignnone size-full wp-image-74" title="005" src="http://www.thetechlabs.com/wp-content/uploads/2008/07/005.png" alt="" width="500" height="94" /></p>
<p>The email explains us about the service, and there&#8217;s three important things to see in here:</p>
<ul>
<li>Where to download the weather.com SDK (http://download.weather.com/web/xml/sdk.zip)</li>
<li>The weather.com XML Partner ID &amp; License Key</li>
<li>How to make a properly formatted XML request for the service</li>
</ul>
<p><img class="alignnone size-full wp-image-75" title="006" src="http://www.thetechlabs.com/wp-content/uploads/2008/07/006.png" alt="" width="500" height="202" /></p>
<h3>Contents of the wheater.com SDK</h3>
<p>On this package you gonna find a PDF, with the license agreement and some useful information about how to make a request for the services,<br />
and two folder, one with the weather.com logos, and the other with the weather icons we gonna use on this tutorial as reference.<br />
There&#8217;s 3 type of icon sizes, for this tutorial we gonna use the 93&#215;93 icons.</p>
<p>The icons are not too fancy, so we could download a free cool set of weather icons from here:</p>
<p><a href="http://liquidweather.net/icons.php#iconsets" onclick="javascript:pageTracker._trackPageview('oclicks/http://liquidweather.net/icons.php#iconsets');">http://liquidweather.net/icons.php#iconsets</a></p>
<p>This iconsets and backgrounds are from the Liquid Weather++ appi.</p>
<h3>Setting up our api key</h3>
<p>We could put all our data inside flash, like the code of our city, our partner id, and so on, but it&#8217;s gonna be a pain in the ass every time we want to change it.<br />
So, it&#8217;s much better if we load this type of data externally form an XML file. The XML structure should looks like this:</p>
<pre>	ARBA0009
XXXXXXXXX
	XXXXXXXXXX
	m</pre>
<h3>Loading our data in Flash</h3>
<p>Now our hands on AS.</p>
<p>We gonna do all the programming in just 2 frames, pretty easy.</p>
<p>On the first frame, we load all the data to use it when we call the weather.com xml service.</p>
<p>On the second frame, called &#8220;weather&#8221;, we load the weather.com xml and display the data.</p>
<p>So, in our first frame:</p>
<ul>
<li>We define the variables we gonna use</li>
<li>We call the xml that holds our data</li>
<li>Then we pass the data from the xml to our variables</li>
<li>And if everything it&#8217;s oki, we could go to the weather frame</li>
</ul>
<p><img class="alignnone size-full wp-image-76" title="007" src="http://www.thetechlabs.com/wp-content/uploads/2008/07/007.png" alt="" width="301" height="208" /></p>
<pre>stop();

//=================
//ini variables
//=================

//we define our variables to be loaded

var city:String;
var par_id:String;
var key:String;
var units:String;

//call the xml with our data

var data_xml_url:String = "data.xml";
var user_data:XML = new XML();
var data_url:URLRequest = new URLRequest(data_xml_url);
var dataLoader:URLLoader = new URLLoader(data_url);

dataLoader.addEventListener(Event.COMPLETE, dataLoaded);

function dataLoaded(e:Event):void
{
	user_data = XML(dataLoader.data);

	//pass the data from the XML to our variables

	city = user_data.city.toString();
	par_id  = user_data.parid.toString();
	key  = user_data.key.toString();
	units  = user_data.units.toString();

	//if everything it's oki, we could go to the weather frame

	gotoAndStop("weather");
}</pre>
<h3>The weather icons</h3>
<p>To display the different type of weather, we need a movieClip that holds all the possible weathers, there&#8217;s not too much, just 47.<br />
So, we create a new movieclip and call it &#8220;icons_mc&#8221;, and inside the icons_mc we import all the icons from the Weather.com SDK icons folder,<br />
or from the cool icons from liquidweather. There&#8217;s a lil bit differences between the Weather.com SDK icons and the liquidweather icons.<br />
On the weather.com SDK, the icons 25 and 44 are N/A, if you gonna use the liquidweather icons, just replace the 25 and 44 icons with the N/A png.</p>
<p>Don&#8217;t forget to put a stop(); in the first frame of the icons_mc, so the MC start stopped.</p>
<p><img class="alignnone size-full wp-image-77" title="008" src="http://www.thetechlabs.com/wp-content/uploads/2008/07/008.png" alt="" width="500" height="491" /></p>
<h3>Loading the weather.com xml service</h3>
<p>Now we could load the data from weather.com</p>
<p>We allow our swf to make calls from the domain &#8220;xoap.weather.com&#8221;, we make the icons_mc MovieClip invisible, because we don&#8217;t know which icon use yet, and we compose the weather xml url with the variables from the frame 1.</p>
<pre>stop();
//=================
//allow domains
//=================
Security.allowDomain("*", "xoap.weather.com");
//=================
//ini settings
//=================
icons_mc.visible = false;
//=================
//XML
//=================
var weather_xml_url:String = "http://xoap.weather.com/weather/local/"+city+"?cc=*&amp;link=xoap&amp;par="+par_id+"&amp;key="+key+"&amp;unit="+units;</pre>
<p>The xml from weather.com have this structure with some interesting data. As you can see there&#8217;s a lot of useful data to load, but we gonna load just the necessary by now.</p>
<p>Later you could play with it and make an advanced one.</p>
<pre>    en_US
<form>MEDIUM</form>

    C
    km
    km/h
    mb
    mm

    Buenos Aires, Argentina
    1:39 PM
    -34.61
    -58.37
    8:01 AM
    5:52 PM
    -3

    6/27/08 1:00 PM Local Time
    Buenos Aires Air Park, Argentina
    13
    13
    Fog
    20

      1021.0
      falling

      11
      N/A
      360
      N

    82
    2.5

      <em>2</em>
      Low

    10

      23
      Waning Crescent</pre>
<h3>Displaying the data</h3>
<p>To display the data, we have three different sprites:</p>
<ul>
<li>The icons MovieClip</li>
<li>A dynamic text field to load the outside temp called &#8220;temp_txt&#8221;</li>
<li>A dynamic text filed in the bottom to make a lil speech about how feels to be outside called &#8220;info_txt&#8221;</li>
</ul>
<p><img class="alignnone size-full wp-image-77" title="009" src="http://www.thetechlabs.com/wp-content/uploads/2008/07/009.png" alt="" width="500" height="491" /></p>
<p>Our main interest is on the XML file on the icon number, so we could show the right icon.</p>
<p>We load the xml using our well formatted &#8220;weather_xml_url&#8221;, and traverse the xml three to find what we are looking for.</p>
<p>In this step we:</p>
<ul>
<li>we load the temp on the temp_txt text field</li>
<li>make the icons visible, load the icon number and tell the icons:mc to stopn on thet icon frame</li>
<li>and finally we set the complementary text</li>
</ul>
<pre>var weather:XML = new XML();
var weather_url:URLRequest = new URLRequest(weather_xml_url);
var weatherLoader:URLLoader = new URLLoader(weather_url);

weatherLoader.addEventListener(Event.COMPLETE, weatherLoaded);

function weatherLoaded(e:Event):void
{
	weather = XML(weatherLoader.data);

	//we load the temp on the temp_txt text field
	temp_txt.text = weather.cc.tmp;

	//we make the icons visible, load the icon number and tell the icons:mc to stopn on thet icon frame
	icons_mc.visible = true;

	var weather_icon:int = Number(weather.cc.icon.toString())+1;
	icons_mc.gotoAndStop(weather_icon);

	//and finally we set the complementary text
	var ud:String = weather.head.ud;
	var us:String = weather.head.us;

	var city:String = weather.loc.dnam;
	var time:String = weather.loc.tm;
	var temp:String = weather.cc.tmp;
	var flik:String = weather.cc.flik;
	var term:String;

	if (temp == flik)
	{
		term = "and it feels like "+flik+" degrees,";
	} else {
		term = "but it feels like "+flik+" degrees,";
	}

	var wind_v:String = weather.cc.wind.s;
	var wind_gust:String = weather.cc.wind.gust;
	var wind_d:String = weather.cc.wind.d;
	var wind_t:String = weather.cc.wind.t;

	var hmid:String = weather.cc.hmid;
	var vis:String = weather.cc.vis;

	info_txt.text = "It's "+time+" here in "+city+". It's "+temp+" degrees out there "+term+" the wind blows from the "+wind_t+" at "+wind_v+" "+us+", the humidity is "+hmid+"% and the visibility is "+vis+" "+ud+".";
}</pre>
<p><img class="alignnone size-full wp-image-79" title="010" src="http://www.thetechlabs.com/wp-content/uploads/2008/07/010.png" alt="" width="212" height="258" /></p>
<p>Now we could export our movie and if it&#8217;s cold outside, it&#8217;s good to be inside.</p>
<h3>Final thoughts</h3>
<p>We gonna need to know the international code of our city, so we could go to</p>
<p><a href="http://www.weather.com/common/welcomepage/world.html" onclick="javascript:pageTracker._trackPageview('oclicks/http://www.weather.com/common/welcomepage/world.html');">http://www.weather.com/common/welcomepage/world.html</a></p>
<p>Search for our city, and find the code on our address bar. I know it&#8217;s a lil bit tricky but it works fine.</p>
<p><img class="alignnone size-full wp-image-69" title="011" src="http://www.thetechlabs.com/wp-content/uploads/2008/07/011.png" alt="" width="353" height="72" /></p>
<p>Hope you enjoyed this lil tutorial as much as I enjoyed writing for you.</p>
<p class="addtoany_share_save_container">
    <a class="a2a_dd addtoany_share_save" onmouseover="a2a_show_dropdown(this)" onmouseout="a2a_onMouseOut_delay()" href="http://www.addtoany.com/share_save?sitename=The%20Tech%20Labs&amp;siteurl=http%3A%2F%2Fwww.thetechlabs.com%2F&amp;linkname=Creating%20a%20Weather%20Widget%20with%20XML%20and%20AS3&amp;linkurl=http%3A%2F%2Fwww.thetechlabs.com%2Fxml%2Fcreating-a-weather-widget-with-xml-and-as3%2F" onclick="javascript:pageTracker._trackPageview('oclicks/http://www.addtoany.com/share_save?sitename=The%20Tech%20Labs&amp;siteurl=http%3A%2F%2Fwww.thetechlabs.com%2F&amp;linkname=Creating%20a%20Weather%20Widget%20with%20XML%20and%20AS3&amp;linkurl=http%3A%2F%2Fwww.thetechlabs.com%2Fxml%2Fcreating-a-weather-widget-with-xml-and-as3%2F');"><img src="http://www.thetechlabs.com/wp-content/plugins/add-to-any/share_save_171_16.gif" width="171" height="16" alt="Share/Save/Bookmark"/></a>

	</p><img src="http://feedproxy.google.com/~r/TheTechLabs_webservices/~4/pxYdTWz7MLg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.thetechlabs.com/xml/creating-a-weather-widget-with-xml-and-as3/feed/</wfw:commentRss>
		<feedburner:origLink>http://www.thetechlabs.com/xml/creating-a-weather-widget-with-xml-and-as3/</feedburner:origLink></item>
	</channel>
</rss>
