Tutorial: Pull Twitter Updates into Flash

Fwitter

That’s right – i said “Fwitter”

It’s a very simple thing to display your Twitter updates in a Flash widget. We’re going to use the xml feed, because that’s what i’m most comfy with. Unfortunately, you can’t grab the xml feed from Twitter’s site, because they’ve locked their crossdomain policy file … but you can pull down the data using any other damned process. Here’s the basic flow you have to follow:

  1. Hit a PHP page or javascript function from Flash (we’ll use PHP)
  2. Parse the XML data that the call returns
  3. Display the goodies in your Flash app

Here Comes the Code

This is the Actionscript 3 code you’ll need:

package
{
	/**********************************************
	 * 
	 *  This fun Twitter widget is brough to you
	 *  by Untold Entertainment Inc, and 
	 *  peanut butter!  Peanut butter: a gooey,
	 *  yummy snack that might kill you.
	 * 
	 *  http://www.untoldentertainment.com
	 * 
	 **********************************************/
	
	// Here are all the goodies you're going to need 
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.events.Event;
	
	public class Main extends MovieClip
	{
		private var twitterXML:XML; // This holds the xml data
		
		public function Main()
		{
			// Put your Twitter username here.  For example, ours is "untoldEnt" :
			var myTwitterID:String = "myTwitterID"; 
			// Put the path to your php script here:
			var twitterPHPScriptPath:String = "http://www.yourdomain.com/thePathToYourPHPScript";
			// Fire the loadTwitterXML method, passing it the url to your Twitter info:
			loadTwitterXML(twitterPHPScriptPath + "?twitterId=" + myTwitterID);
		}
		
		private function loadTwitterXML(URL:String):void
		{
			var urlLoader:URLLoader = new URLLoader();
			// When all the junk has been pulled in from the url, we'll fire finishedLoadingXML:
			urlLoader.addEventListener(Event.COMPLETE, finishLoadingXML);
			urlLoader.load(new URLRequest(URL));			
		}
		
		private function finishLoadingXML(e:Event = null):void
		{
			// All the junk has been pulled in from the xml!  Hooray!
			// Remove the eventListener as a bit of housecleaning:
			e.target.removeEventListener(Event.COMPLETE, finishLoadingXML);
			
			// Populate the xml object with the xml data:
			twitterXML = new XML(e.target.data);
			showTwitterStatus();
		}
		
		private function showTwitterStatus():void
		{
			// Uncomment this line if you want to see all the fun stuff Twitter sends you:
			//trace(twitterXML);
			
			// Prep the text field to hold our latest Twitter update:
			twitter_txt.wordWrap = true;
			twitter_txt.autoSize = TextFieldAutoSize.LEFT;
			
			// Populate the text field with the first element in the status.text nodes:
			twitter_txt.htmlText = twitterXML.status.text[0];
		}
	}
}

And here’s the PHP code:


Et voila! Your latest Twitter update appears in a text box on the stage.

[SWF]http://www.untoldentertainment.com/blog/tutorials/twitter/twitterUpdatesInFlash.swf, 550, 100[/SWF]

(note: this tutorial assumes you have a textField on the stage named “twitter_txt”)

Twitter exposes a pile of other information, including time stamp, post count, number of followers, etc etc that you can play around with. This simple example should get you started, anyway.

You can download the source code here:

twitterUpdatesInFlash.zip

Big thanks to Jeffie G for writing the PHP code to circumvent Twitter’s silly security restriction.

Don’t miss the second part of this tutorial:

Tutorial: Twitter Updates in Flash Part 2

For more Flash AS3 Tutorials and a pile of other useful stuff, check out our Flash and Actionscript 911 feature.

142 thoughts on “Tutorial: Pull Twitter Updates into Flash

  1. Ron

    Hi Ryan,

    I am a bit confused and i who’d appreciate any help you might give.
    It seems that i don’t have any of the classes required for this project to work. i just cannot find them.
    I assume that this question derives from my lack of knowledge in flash, but where do i get the necessary classes.

    P.S
    i checked in : Local Settings\Application Data\Adobe\Flash CS3\en\Configuration\Classes
    and there are just few files under that directories i have net,text,display but none of the files there has the relevant names

    Any help would be appreciated
    Thanks.

    Reply
    1. Ryan

      i’m not too sure what your question is, Ron. The only classes you need are the ones we provided in the .zip file at the end of the tutorial. If you’re having a problem with thos import statements, you shouldn’t – any *legal* copy of Flash ships with all of the internal classes you need.

      If you’re not pointing your file to a document class (in the Properties panel) but are rather writing your code straight in the Flash IDE, you don’t need import statements. Everything is assumed imported.

      Hope that helps.

      Reply
  2. Ron

    Hi Ryan,

    I am a bit confused and i will appreciate any help you might give.
    It seems that i don’t have any of the classes required for this to work. i just cannot find them.
    I assume that this question derives from my lack of knowledge in flash, but where do i get the necessary classes.

    P.S
    i checked in : Local Settings\Application Data\Adobe\Flash CS3\en\Configuration\Classes
    and there are just few files under that directories. nothing close to what i need to this project.

    Thanks.

    Reply
  3. Rob

    Hey Ryan, I’ve got this working in AS3 but has anyone gotten an AS2 version working? Can it show more than the latest tweet?

    Reply
    1. Ryan

      That’s good news!

      The php script should return xml-formatted data with the last 20 tweets, along with information about the tweet time and date, etc.

      Reply
  4. Codetarded

    I’m overlooking something simple here, I know. I’ve input the values for my Twitter, the php file, etc.. possibly in that I have no idea how the package path part works and I’m growing entirely confused. How does the main.as file work with the dynamic text object (I’ve got a movieclip set up in my swf)?

    I’m an art guy, who can work html and css just spiffily, but this stuff, after a good 5 hours of poking at it, has fried my brain entirely. Just trying to set up a little flash-based folio and I’ve got EVERYTHING else working but the pretty little twitter bar I’d planned. Any help you can offer for the completely stupid? Syntax of the commands that need to be changed or altered for this code to work? Anything would be helpful.

    Also many, many thanks for the commented lines. They DO help me learn bit by bit what all these foreign words mean.

    Reply
    1. Ryan

      Codetarded – (my new favourite user name)

      When you define Main.as as the base class, it’s essentially the same as writing code on the first frame of your main timeline in the Flash IDE, except that you need to follow the proper class structure. That means putting “package {}” at the top, and “public class Main extends MovieClip {}” inside those curlies, etc. You also have to use import statements above the class declaration to tell the compiler which chunks of code you’ll be using. Why waste time and space compiling it if you don’t need it, right?

      So because Main.as now acts as a surrogate for the main timeline in your Flash file, you can just refer to your dynamic text field by name. If it’s on the stage, and it exists in the first frame, and it’s got the instance name “heyNonnyNonny”, then you can just say “heyNonnyNonny.text = ‘Hello world’” from within your Main.as file.

      Does that help at all?

      Uber important: one thing you may have forgotten is to tell Flash that you’re using the Main.as file as the point of entry, instead of the main timeline. You can find the Base Class declaration field in the Flash IDE’s Properties panel.

      - Ryan

      Reply
  5. Codetarded

    It’s something to start with certainly! I certainly didn’t tell Flash that Main.as is the point of entry, nor did I have the package right or anything. It’s a huge help and I really appreciate it! Not to mention the fast response!

    Fingers crossed that when I jump back into this and try to hammer this out, the results will be better.
    Thanks again!

    Reply
  6. jamie

    This is something i have been looking for, thanks, but i have spent hours trying to get it to work. I have tried using is as classes and also putting the Main.as in the timeline where the movie clip is.

    I keep getting the errors
    1114: The public attribute can only be used inside a package
    5000:the class ‘Main” must subclass ‘flash.display.MovieClip….

    I have kept the code as it appears above on the first line:
    package {
    because all of my files are within the same folder.
    I think that this may be causing the error tho?

    Any help would be appreciated

    Jamie

    Reply
    1. Ryan

      The 5000 error means exactly what it says: Main must subclass MovieClip.

      public class Main extends MovieClip

      The 1114 error probably popped up because your brackets are messed up. package comes first, with its two curly brackets. Inside those brackets are the import statements and the class declaration. The class declaration has two curly brackets. Inside those are the method declarations, field definitions, and the constructor function.

      This is all Actionscript 101 stuff, though. If you’re having trouble with the basic structure of a Flash project, like a few other people in this thread, this tutorial probably isn’t the first thing you’ll want to jump into.

      - Ryan

      Reply
    1. Ryan

      Take a look at this line:

      twitter_txt.htmlText = twitterXML.status.text[0]
      

      [0] refers to the first item in the list. Use [1], [2], etc t refer to the other items. So you could just daisy chain them into the same field separated by a space and a comma. That’s one way:

      twitter_txt.htmlText = twitterXML.status.text[0] + ", " + twitterXML.status.text[1] +", " + twitterXML.status.text[2];
      

      Scour the Internatz for a tutorial on Arrays to figure out how to work with this kind of data.

      - Ryan

      Reply
  7. ozgur uksal

    If any one needs the crossdomain.xml on the twitter server, it is in (some nonsense domain that i edited out – Ryan)

    Reply
  8. ozgur uksal

    Ryan- I see that you have no experience loading user icons from twitter to your flash app. Since your flash app is expected to run in a domain in where the twitter user icons are hosted on another domain, you would need my “*NONSENSE*” domain. Your link doesn’ t help anyone, but mine would.

    Reply
  9. ozgur uksal

    Do you have any solution to load user icons from twitter? I see that you only load and display status. Please, share your experience with the community if you know how to load user icons rather than loading basic text.

    Reply
    1. Ryan

      ozgur – No need to get hostile. Your original comment didn’t say anything about loading Twitter user icons – it just said “this is the crossdomain.xml on the twitter server”, and then you provided a link to a file that was NOT the crossdomain file on the Twitter server. So my Spidey sense tingled.

      What you’re saying is that you want to share a way to load the user icons from Twitter, and since Flash gets sticky about loading images from other domains, you were providing an example of a crossdomain policy file someone could upload to his own server to allow the Flash app to load the Twitter user icon images. Why didn’t you say so? The app i built doesn’t require this, because i’m only ever displaying my own Tweets. But it’s definitely a valuable tip.

      Please re-share – it’s a worthwhile point. Sorry for the confusion.

      - Ryan

      Reply
  10. Aaron

    I actually started off with computer science in college but math is for the birds! (tweet tweet), okay, really bad attempt at a pun (or does that even qualify?)…

    TY for answering and the info on the array. I’ve been meaning to do more with actionscript 3.0, I have books by Colin Moock sitting around my desk that I’ve been meaning to finish! But with the digital blob available to us all, people ahead of the game and writing how-to’s, kinda saved me time and all, freaking google found you, it’s google’s fault. Appreciate it!

    Reply
  11. Tommaso

    Any ideas why my page shows up completely blank when I upload it to the server? It works fine in the IDE, troublesome in the SWF player, and nothing at all on the web server.

    I noticed a post early on about this, but didn’t see what was fixed. I converted your tutorial to make myself an AS2 version. Maybe I’ve run into a security issue?

    Reply
    1. Ryan

      Tommaso – try this:

      File>Publish Settings>”Flash” tab

      Find the “Local playback security” drop-down, and change it from “Access local files only” to “Acess network only”. It’s all-or-nothing with Flash, so you can’t mix local files with network files.

      - Ryan

      Reply
  12. Tommaso

    Wow you’re fast. And a life saver. That worked! Yours is the best tutorial on this out there. Thanks for taking the time and being so supportive!

    Reply
  13. Brandon

    This tutorial would actually help the people that are trying to use it if you would EXPLAIN what to do with each set of scripts instead of just throwing it out there and letting everyone get tons of errors.

    Reply
    1. Ryan

      Sorry, Brandon – this tutorial presumes a basic knowledge of Flash and PHP. Note that we also didn’t teach you how to use a computer or READ in the tutorial either.

      Reply
  14. Randy

    At the risk of sounding retarded, I still don’t get how to do this with AS 2, and I don’t know where to go for the proper “documentation”, as you told andres. Could you point me in the right direction?

    Reply
    1. Ryan

      Randy – if you’re using CS3, the documentation is right there in Flash. Just look through the Help menu. You need to research how to 1) make a Javascript call from Flash, and 2) how to pull in and parse an XML file. Beyond the official documentation, there are scads of examples online. Those are some search terms to get you started on your merry hunt.

      Reply
  15. Andy

    Question: if I already have a document class called Main, can I incorporate this code into my class and it still work or can I rename this as a new class….what extent do I need to go to in order to do that?

    Reply
  16. Trevor Ferkler

    Im not the most experienced Flash designer so this question is probably pretty obvious. I am still using AS2. I want to bring my twitter feed into my new flash site. I have a basic understanding of how to do this based on the information you provided. Am I able to design a custom box into my flash site that houses my twitter feeds? Even if it is just a text box over some kind of design element that is consistent with the design of my site? Does this question make sense at all?

    Reply
    1. Ryan

      Trevor – yep. You can totally do that. Flash is so cool, you can have the text of your Twitter messages march around the edge of a streaming video player carrying little swords if you want to. But that’s beyond the scope of this tutorial.

      - Ryan

      Reply
  17. Arnold

    Hi, Great stuff first of all! I like it alot!

    I have a little trouble converting the code for it to work with AS2. I saw you helped a guy out here and was wondering if you could do the same with me?

    If you could send me an email it would be great

    Appreciate it

    Reply
    1. Ryan

      Arnold – if i helped him at all, it was by kicking his ass out the door :) i try not to touch AS2 unless absolutely necessary. But if you break this whole thing down into concepts, just research those concepts in AS2 and you should be able to put this together.

      Reply
  18. markus

    im getting your twitter status’ even when i change the code to get my twitter status’ ..what could i be doing wrong?

    Reply
    1. Ryan

      Mike – the links are in the xml. So in Actionscript, i scan the Tweet for instances of “http”. i wrap any complete word (a word is a string that is surrounded by a space on either side) with an html a href tag. i make sure the text field is fed htmltext instead of text, and voila – the links are clickable.

      I do something similar to link to people’s Twitter names. i look for anything starting with an “@” symbol, and then i wrap that in an anchor tag and link to twitter.com/thatPersonsTwitterName.

      Hope that helps.

      Reply
  19. Mike Maurer

    totally helps…that’s what i was already doing…but was hoping there was html in the xml feed for some reason…

    thank you

    Reply
  20. mike maurer

    ryan…i’ve pasted the .php code and uploaded it to my server…when i hit it i get this error..

    Parse error: syntax error, unexpected T_VARIABLE in /home/.featherweight/mrtyque/mikemaurerdesign.com/proxy/twitter_updates.php on line 3

    any ideas?

    Reply
  21. Pingback: untoldentertainment.com » Tutorial: Clickify Your Twitter Feed in Flash

  22. Pingback: Remco Janssen’s Blog » Blog Archive » Gastles ROC Nijmegen

  23. steve p

    Hi Ryan

    Trying to figure out how to make the tweet links clickable. I read through the comments and I think I get what needs to be done just not sure how to say it in AS3. Basically using an if statement you check each word loaded into the dynamic text box for “http://”? And if that string is found you somehow put anchor tags around the word?

    Reply
  24. Victoria

    Did anyone ever figure out how to do this is AS2? I’m stuck having to convert a project from AS3 to AS2 and this widget is involved…i’ve looked through the documentation in CS3 and also searched the web but i just don’t have the coding skills to pull it off. Does anyone have anything I could cut and paste?

    Reply
    1. Ryan

      Victoria- i’ve got an even better idea. Why don’t you just cancel your contract with the client, and i’ll wire your living expenses directly into your bank account?

      Seriously – meet me halfway here. It’s not that difficult to learn how to call a URL and parse XML in AS2.

      Reply
  25. Victoria

    Ryan-
    This isnt for pay — I wish! And I’m just the designer who got roped into trying to figure this out, so my coding experience isn’t much… We dont have anyone who teaches this stuff here in Panama, but if it really isnt that difficult, maybe I could figure it out somewhere online…any suggestions?

    Reply
    1. Ryan

      Victoria – Yep! Just Google “flash xml parsing tutorial”. There’s LOTS of info out there. Make sure you’re looking at an AS2 tutorial.

      Also, i take requests for tutorials. If there’s something you want to learn, i’ll definitely consider teaching it here on the site. (But PLEASE don’t make me revert to AS2! :)

      - Ryan

      Reply
  26. Paveloosha

    Hi Ryan, Thanks a lot for this work. It is working in AS 3.0 but I tried a lot to get it work in AS 2.0 but it is not working. Please provide a solution for us who uses AS 2.0 till now.

    -Pavel

    Reply
    1. Ryan

      Paveloosha – asking me to go back to AS2 is like asking me to build a Mars probe out of hand-churned butter. i decline.

      Reply
      1. G

        What a AS2 hater!

        You know there are still many websites out there built with AS2, therefore having an AS2 version of the Twitter widget is only understandable. Then the widget could be loaded into a Flash website build in AS2…

        Reply
  27. alekbirdie

    hi Ryan, im very excited for getting this done! but really i read all commments a do a lot, even so i have this error on flash, and also if i upload all to the server, the same error, hope you can help me…

    TypeError: Error #1088: El marcado del documento que sigue al elemento raíz debe estar bien formado.

    any ideas?
    thanks

    Reply
    1. Ryan

      alekbirdie – That’s a malformed xml error, is it not? Are you getting that from the Twitter feed, or have you substituted your own xml file?

      Reply
  28. Pingback: Craig Massingham — Task 14

  29. t19media

    Has the source file been updated after this post? I don’t see the point of the php script to get the url when it is already defined in the .as file. Am I missing something here?

    Reply
  30. FunkyMonk

    Hey Ryan,

    I seem to have only one problem:

    Scene 1, Layer ‘Actions’, Frame 1, Line 2 1037: Packages cannot be nested.

    I really don’t understand this, I’ve copied your code exactly and only changed the Twitter user ID and PHP URL.

    Any ideas?

    Reply
    1. Ryan Henson Creighton

      i usually get unhandled stream errors when either my Internet connection or the stream source are down (Twitter problems?), or when i pee with my hands behind my head. Confirm that the address actually works by punching it into the browser (i just did, and it does … )

      Reply
  31. Joe Allison

    Hi there, I manged to get this working, thanks very much! great tutorial.

    I now want to be able to put another twitter feed into another dynamic text field in the same document. Basically I want to be able to publish several latest tweets by several different dwitter users. I have tried to duplicate parts of the code myself but I’m just guessing.

    I’m a graphic design student studying in my final year at university in Bristol England, and I really need to try and crack this for my final project. I only have six weeks left! Please Please Please help me :)

    —Joe

    Reply
    1. Ryan Henson Creighton

      Hey, Joe. i got your email too.

      i haven’t been in the code in a LONG time, but try something like this:

      1. Store a list of the feeds you want to pull from in an array.
      2. Loop through the array. With each feed:
      i. Pull in the data.
      ii. Parse it so that you store all of the tweets as objects in an array.

      When you’re done, you’ll have an array filled with tweets from various sources.

      Reply
  32. Pingback: Sket på nettet den 16.06.11

  33. James

    I already found the problem :P It’s in a movie clip!
    So firstly the clipname and then the Instance name!
    Im sorry for spamming ;D

    Reply
  34. Clayton

    Hey Ryan, love the tut! I’ve only been using AS3 for a few months but seem to be getting the hang of it pretty well. The one problem I keep having is “1120: Access of undefined property of twitter_txt”. I have my text field instance named “twitter_txt”. I’m kinda stuck, any ideas?

    Thanks!

    Reply
    1. Clayton

      So today I downloaded your source code files above, but instead of using the code in the download I used your code from above and plugged in my twitter id and the url for my php file in the Main.as and then tested the “twitterUpdatesInFlash.fla” and I get this:
      TypeError: Error #1090: XML parser failure: element is malformed.

      at Main/finishLoadingXML()
      at flash.events::EventDispatcher/dispatchEventFunction()
      at flash.events::EventDispatcher/dispatchEvent()
      at flash.net::URLLoader/onComplete()

      Is this saying that it’s not reaching my .php file or Twitter’s XML? Or maybe something altogether different? I’m confooosed . . .

      Reply
  35. Pingback: How to Add Your Twitter Feed to Your Website

  36. Solarix

    I’m pretty new at this. I was looking at the Main.as and the fla and I didn’t find anything in the fla that connects with the Main.as. I would greatly appreciate any information anyone has.

    Reply
    1. Ryan Henson Creighton Post author

      A colleague of mine asked me about a very similar problem, except that in his case, Apple refused to approve his game, and there was nothing he could do about it. i don’t have any solutions yet, but i have my ear to the ground. Please let me know if you solve the problem!

      - Ryan

      Reply
  37. Simon

    Thanks for the example.

    One thing – the sample I downloaded does not use the PHP.

    Secondly – the url you are using in the PHP no longer returns a page. Do you have any idea what the new format of the url should be please?

    from a browers:

    Sorry, that page does not exist

    or via the PHP call in Flash:

    Warning: file_get_contents(http://twitter.com/statuses/user_timeline/29754661.xml): failed to open stream: HTTP request failed! HTTP/1.0 404 Not Found

    in /var/www/02/08/35/xxxxxxxx.info/www/twitter/twitterfeed.php on line 7

    Reply
  38. Jayme

    Hey there! I just wanted to ask if you ever have any trouble with hackers?
    My last blog (wordpress) was hacked and I ended up losing several
    weeks of hard work due to no backup. Do you have any methods to stop hackers?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>