Home  >  

Send Gifts Component

Author photo
AddThis Social Bookmark Button
     Sending gifts and items are one of the favorite actions among the millions of facebook users. Friends send items to friends, "buy" gifts, "sell" virtual items etc. Honestly I am not engaged in this activity a lot on facebook, but the number of people willing to send virtual gifts, buy virtual goods is shockingly high! So this article might be underestimated on the first sight, but because I am aware of the trend of sending and receiving gifts, it is worth writing a complete article that covers the trend in actionscript. The number of possible implementations for this component is really countless and in this article we will be able to show only few of them.

article15_img30.png
Here is how we are going to create this. There will be a php layer that will read the contents of the folder containing images. Those images represent gifts. In order to this to work, we need to set up AMFPHP. We will not repeat ourselves as we discussed this already in the first article. We assume that you completed the 3rd article (http://www.insideria.com/2009/04/setting-up-amfphp-for-flash-an.html) and have the AMFPHP up and running. The point we need to concentrate on is the new PHP class file that will work with our application. So, let's create it now.
Open your favorite text editor. Here is EditPlus on my side:

article15_img2.png
Ok, create a new PHP file:

article15_img3.png
The class that we will be creating will be called GiftReader and that will also be the name of the PHP class. Here is the very basic structure:

<?php

class GiftReader {
 
     function GiftReader(){
      }
 
}

?>
This is the basic class along with the constructor. Next this we need to do is to upload it and check if there are any errors. So, upload it to the amfphp/services/ folder of the application folder. Run http://yourServer.com/yourAppName/amfphp/browser/index.html in the browser and check if you have the same result as below:

article15_img4.png
If we have the result like on the image, then it is the sign that we are on the right path! We can safely move on to the next step. The next step would be to create the method that will open the folder that contains images etc. and pass the files as array to flash. This will make the maintenace a lot easier then having an xml the list of files. How does the method look like? Well the method has those lines of code:


function readFolder($folder){
 		$d = dir("../../".$folder) or die("Wrong path: $image_file_path");
 		while (false !== ($entry = $d->read())) {
  			if($entry != '.' && $entry != '..' && !is_dir($dir.$entry))
  				$images[] = $entry;
  		}
 		$d->close();
 		return $images;
 	}
In order for this to work, we need to have one „images“ folder inside our main application folder. The path to the images folder should be: http://www.yourServer.com/yourApp/images/. Inside that folder, we need to have images that will represent the items in the facebook application. For now, I just put put one dummy image to check if the function really works.

article15_img5.png
That's enough for the start. Now let's see if the function really works. Refresh the ClassBrowser and the new methods should be visible immediately:

article15_img6.png
By typing the folder name inside the field

article15_img7.png
and pressing Call we get the following result:
Finally we got a function that reads the contents of the folder and returns it as an array! Wow, instead of creating messy xml files that need to be updated every time we add new images, this approach makes our lives much easier as we onyl need to upload new images and the php will always read all images from the folder.
So, by now we have a better sense of how the application will actually work. Here is the image that explains it better in detail:

article15_img8.png
Now, how does this apply to Flash? The Flash front end will act as the window for the images. Here are some examples of images in Gift applications:

article15_img10.png
This image above is from the popular gifts application that has a lot of users and the gits are really simple images as you can see.

article15_img11.png
Here is an another collection of nice gifts in the even more popular Free Gifts application. There are lots of other stuff we need to be aware of when developing such an application. In such case, we want to have rodays birthdays displayed, we want to have the news published when we send public gifts to someone, or even not if the gift is private. We also want to be able to categories the gifts and also we want to be able to search for gifts. Another great idea would be to display suggestions of newest gifts, or display gifts based on the preferences of the users. But now let's get back to reality and try to display the gifts inside the swf.
In order to work on this, we need to open the fla we worked on previously.Open the FLA and remove all elements from the stage.

article15_img12.png
Next thing to do would be to connect to AMFPHP correctly. We already did that several times, here is the reminder:


import flash.net.*;

var conn:NetConnection = new NetConnection();

conn.connect("http://www.yourServer.com/yourApp/amfphp/gateway.php");
Only those 2 lines of code are neccessary and we already connected to AMFPHP. We will not change anything in the lines above for the entire article and we will always use the conn property to make the method calls defined in the PHP class file.
Now we will call the much discussed readFolder() method and see if the array of items actually arrives on the swf side. Here is the line of code that will make the call:


conn.call("GiftReader.readFolder", folderResponder, "images");
And the complete frame 1 now looks like this:


import flash.net.*;

var conn:NetConnection = new NetConnection();

conn.connect("http://yourServer.com/yourApp/amfphp/gateway.php");

var folderResponder = new Responder(onResult, onFault);

conn.call("GiftReader.readFolder", folderResponder, "images");

function onResult(result){
 	trace(result);
}

function onFault(result){
 	trace("onFault: " + result);
}
Let's see if this actually works. We need to upload and run it inside the facebook canvas. Here is how it looks like in my window:

article15_img13.png
Cool, finally there is the array of images. We can now work with the images just like with normal ActionScript arrays because AMFPHP did the conversion, no need for XML files here. What's next for us?
Next think we need to do is to display the images in a fashion that fits our needs. For this, it's best to create a small component that will be resizable and flexible. In good software engeneering practices they say it's not good to repeat ourselves, so we will not repeat ourselves in this case. It's would be best to use components that already exist and add additional functionality to it. What could be better for this then the TileList component? Here is an image of it:

article15_img14.jpg
Hey, the component seems too have all the stuff we need! It has the feature to scroll up and down, it has the feature the display images and it also givs us the features and abilities to display information about the item, like in this case. So, this leads us to the decision to use the TileList component as the front end for our gifts application! Here is what we need to do in order to display the items correctly.
Well, the first thing we need to do is to work with the very basic TileList. Open the Components panel (Window -> Components)

article15_img14.png
Select the TileList component and drag it on the stage. The size does not matter right now.

article15_img15.png

article15_img16.png
For our tutorial, we need only a few of them. The most important is, however, the dataProvider parameter. Click on the parameter to open the value window.

article15_img17.png
For the beginning, we need to add a sample image for demonstration purposes. Let's add this values:

+
Label: Some Item
Source:  http://www.yourServer.com/yourApp/images/test.jpg
And the result is:

article15_img18.png
Remember that this time we need to set the absolute path to the source image, since facebook application do not recognize relative paths. This is very important to know.

article15_img19.png
Ok, next thing we need to do is to tweak the component so it fits better into the application logic. We need to resize it and also, we need to set the item display to other values, the current settings are not good enough.
Resize the component so it fits the stage.

article15_img21.png
Now when we test the application, the item looks like the following on the image:

article15_img22.png
So, now we have the right look and the right size of the component, it is now almost ready and prepared to work on facebook! But wait, there is one thing to note however. From PHP, we only receive a linear array in form [img1, img2, img3, img4, img5] and the TileList dataProvider accepts an array in the form:


0: label, source
1: label, source
2: label, source

etc. 
It would be cool if we could simply pass the array and the dataProvider handles the rest. Let's extend the TileList component and add the dataProvider we want!
Here is the code:


package {
 
 	import fl.controls.*;
 	import fl.containers.*;
 
 	public class FBTileList extends TileList{
  
  		function FBTileList() {
   			trace("Hi I am: " + this);
   		}
  	 
  	}
 
}
Save this as FBTileList.as in the project folder and change the linkage of the TileList component to FBTileList:

article15_img23.png
Let's check if the component really works with the new class. When compile, you should see the following result:

article15_img24.png
The goal is to have a folder with items like Gift1.jpg, Gift2.jpg, Gift3.jpg. The name of the gift should be stored in the name of the file! Let's say we have 1 gift as image inside our folder. If it is an image of a TeddyBear, we should name it TeddyBear.jpg and upload it to server. The swf file will receive the list of image as array, and the swf needs to fetch those names from the image names. Here is how it can be done. Rename the 1 image file that we use as test to something more meaningful, like „SpecialGift.jpg“.

article15_img26.png
Add the following function to the FBTileList Class:


//set images directly
public function set items(images:Array):void {
 
 			//create new dataprovider
 			var dp = new DataProvider();
 
 			//go through the list of images
 			var i = 0;
 			var len = images.length;
 
 			
 			for(i = 0; i < len; i++){
  
  				//the image file
  				var img = images[i];
  
  				//split to get the name of gift
  				var arr = img.split(".");
  
  				//get the name
  				var name = arr[0];
  
  				//add the image and name to data provider
  				dp.addItem({label: name, source: "http://www.yourServer.com/yourFBApp/images/" + img});
  			}
 
 
 			//finally populate the own dataProvider
 			this.dataProvider = dp;
 
 		}
We may not forget to change the code on the main timeline:


import flash.net.*;

var conn:NetConnection = new NetConnection();

conn.connect("http://yourServer.com/yourApp/amfphp/gateway.php");

var folderResponder = new Responder(onResult, onFault);

conn.call("GiftReader.readFolder", folderResponder, "images");

function onResult(result){
 	//set the images to item
 	tileList_mc.items = result;
}

function onFault(result){
 	trace("onFault: " + result);
}
Now let's see what actually happens:

article15_img27.png
The image appears right on place and also, the name of the image appears directly below! This is cool since we don't have to store the name of the item on any other place like database or xml, we have the image file and the item name stored in one file. We use the image as the actual image file and data storage  Let's try to add more images to see how it behaves. We will add one more image to display it in the swf properly.

article15_img28.png
So, let's see how this looks like in the browser. We just need to refresh it:

article15_img29.png
Wow, it is now soooooooo simple to add new items. What could be easier to upload images to the remote folder?
Next thing we need to do here is to add real gift images, add more functionalyt that we look more like a real facebook gift app!
Here is the sample app that we will be creating:

article15_img30.png
Looks nice, huh?
The flow of the application will be like the following: The user will simply select the list of friends and the gift will be sent out. We will place the MultiFriend component from the last sample and one send button that will send out the gift. We worked hard to create the Multifriend Component, now it's turn to see it in action. Place one MultiFriend component, and one standard button above the TileList. It should look like on image below:

article15_img33.png
Name the button „send_btn“ and the friend component „selectFriend_mc“, respectively. The next thing we need to do is to create a valid facebook session and pass it to the components, so here is how the code on frame one needs to look like:


import flash.net.*;
import com.facebook.Facebook;
import com.facebook.utils.FacebookSessionUtil;

var conn:NetConnection = new NetConnection();

conn.connect("http://yourServer.com/yourApp/amfphp/gateway.php");

var folderResponder = new Responder(onResult, onFault);

conn.call("GiftReader.readFolder", folderResponder, "images");

function onResult(result){
 	tileList_mc.items = result;
}

function onFault(result){
 	trace("onFault: " + result);
}    

var fbook:Facebook;
var session:FacebookSessionUtil = new FacebookSessionUtil("YOUR_API_KEY", "YOUR_SECRET", loaderInfo);
fbook = session.facebook;

selectFriend_mc.load(fbook);
In the facebook window, we should get the following result:

article15_img34.png
When the user clicks on the send button, we simply „ask“ the MultiFriend component to give us the ids selected:


import flash.net.*;
import com.facebook.Facebook;
import com.facebook.utils.FacebookSessionUtil;

var conn:NetConnection = new NetConnection();

conn.connect("http://yourServer.com/yourApp/amfphp/gateway.php");

var folderResponder = new Responder(onResult, onFault);

conn.call("GiftReader.readFolder", folderResponder, "images");

function onResult(result){
 	tileList_mc.items = result;
}

function onFault(result){
 	trace("onFault: " + result);
}    

var fbook:Facebook;
var session:FacebookSessionUtil = new FacebookSessionUtil("YOUR_API_KEY", "YOUR_SECRET", loaderInfo);
fbook = session.facebook;

selectFriend_mc.load(fbook);

send_btn.addEventListener(MouseEvent.CLICK, clicked);

function clicked(e:MouseEvent):void{
 
 	//selected ids
 	trace(selectFriend_mc.selectedFriends);
 	
}
The clicked event is crucial for us. When it is fired, it gives us the ids of all friends selected. What we do with it, it's up to us. Unfortunately we do not have the time and space to discuss the detailed approach to sending and receiving of gifts, but we get the idea. With the ids, we have the opportunity to send emails or notifications to friends. In the previous articles we discussed how to send notifications in great detail. I recommend to use this article to continue with the application. We can send notifications that reference the image being sent etc. but feel free to be creative and make different approaches.
Almost can't believe it but we finished the 15th article! This means that there are 5 left. In the 5 articles that are left, we will go through every step of a facebook application development. We will create an application of medium size that will have all the standard features of a real facebook application. Fortunately there will be enough space in 5 articles to go trough every detail. I'm sure you will enjoy it so be ready next week as we delve deep into the development of a real world application. The application that we will going to create will be called „MovieExpert“, don't miss it, see ya!


To view the entire series please visit http://www.insideria.com/series-facebook-dev.html

Read more from Mirza Hatipovic. Mirza Hatipovic's Atom feed mirzahat on Twitter

Comments

1 Comments

brew norman said:

i think you have to add import fl.data.DataProvider; to the as file.

however, i still get just one image with some label written on in even though there are many image in my images folder.

any suggestions?

Leave a comment


Tag Cloud

Question of the Week: Dream App

If you had an unlimited budget and unlimited resources what application would you build and why would you build it?

Answer

Latest Features

Recommended for You

@InsideRIA on Twitter

Archives

  • Or, visit our complete archive.  

About This Site

Welcome to the premiere community site for all things RIA sponsored by O'Reilly Media and Adobe Systems Incorporated.