26 September 2011
You also need:
- A Facebook account: Sign up
Beginning
Note: This tutorial series was updated September 2011 to use the Adobe ActionScript 3 SDK for Facebook Platform, which uses OAuth 2.0. Facebook is requiring all applications to use OAuth 2.0 by October 1, 2011.
This tutorial series steps you through the process of building and deploying either a desktop or web application that retrieves, displays, and posts Facebook data. In Part 1, you build a local Flex and Facebook desktop application with Flash Builder and the Adobe ActionScript 3 SDK for Facebook Platform. In the process you will:
Note: Facebook frequently changes to the site's user interface and API. This makes it difficult to keep this tutorial 100% up-to-date. Please be sure to add and read the comments at the end of this tutorial for any user interface or API modifications that might have occurred.
In order to build an application that talks to Facebook, you have to have a Facebook account and set up a Facebook application using the Facebook developer application.
If you're new to Facebook, start by creating a Facebook account.
Note: If you already have a Facebook account, you can skip this section and continue with the section "Create a new Facebook application" below.
In order to make calls to Facebook from an application, you must first use the Facebook Developer application to set up the new application.
Note: If you get a message to verify your account, click the mobile phone or credit card link and follow the instructions.
Using Flash Builder, create a Flex desktop application with two states: a login state that displays a login button and a logout state displays a logout button. You will add the Facebook login and logout functionality in the next section.
The first step is to create a Flash Builder project for the application.
The root tag of this main application file is a WindowedApplication tag. Web applications use the Application tag and the application SWF is rendered using Flash Player in a browser window. AIR desktop applications use the WindowedApplication tag and the application is rendered by the AIR runtime in an operating system window.
Next, add a login button to the application and run the application.
<s:Button x="200" y="35" label="Log in"/>
The AIR Debug Launcher (ADL) should open and you should see your text rendered in an operating system window (see Figure 9). The ADL provides a way to test your application during development without having to compile, package, and install the application as a desktop application for testing after every code change.
Next, create two application states: a login state that displays a login button and a logout state that displays a logout button.
label property in this state to Log out.
To communicate with Facebook you use classes in the Adobe ActionScript 3 SDK for Facebook Platform. First, you have to download the classes and make them accessible to your project. Next, you use classes in the library to communicate with Facebook. In this section, you add login and logout functionality. In the following sections, you retrieve and display user information and status messages.
The first step is to download the Adobe ActionScript 3 SDK for Facebook Platform and make its classes available to your project.
Note: If you want to look at the source code, download the source code zip instead (or in addition to the SWC). After unzipping it, copy the com folder and add it to the src directory of your project in Flash Builder. You can then browse the source code for the classes contained in the SWC.
The first step in making calls to Facebook is to create a session that authorizes this instance of your application with Facebook for a specific user. To accomplish this, you use the init() and login() methods of either the FacebookDesktop class (for desktop applications) or the Facebook class (for web applications) of the ActionScript 3 SDK for Facebook Platform.
creationComplete event and generate a creationComplete handler (see Figure 16).
Note: If you do not see the Generate CreationComplete Handler code hint, place your cursor between the quotes and press Ctrl+Spacebar.
Your WindowedApplication tag should appear as shown here:
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" creationComplete="windowedapplication1_creationCompleteHandler(event)">
Your handler should appear as shown here:
<fx:Script>
<![CDATA[
import mx.events.FlexEvent;
protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
// TODO Auto-generated method stub
}
]]></fx:Script>
init() method of the FacebookDesktop class. Force code-hinting to appear by pressing Ctrl+Spacebar and select FacebookDesktop from the pop-up menu (see Figure 17) so that the import is written for you and the compiler can locate the class.
Your code should appear as shown here:
import com.facebook.graph.FacebookDesktop; import mx.events.FlexEvent;
protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
FacebookDesktop.init();
}
Note: The init() method checks to see if there is a shared object (the Flash Player version of a cookie) for this application and if there is retrieves it. If it does not exist, it creates it. The shared object is called com.facebook.graph.FacebookDesktop.sol and contains accessToken and expireDate properties. If the shared object exists and has an access token that has not expired, a call is made to the Facebook Graph API to retrieve the user data associated with this access token. A com.facebook.graph.data.FacebookSession instance is created and populated with the user information. You will look at this user data with the Flash Builder debugger in the next section.
init() method; it has two required arguments. You must pass an application ID and a callback function (see Figure 18).
init()method the application ID and a callback function called loginHandler.FacebookDesktop.init("YOUR APPLICATION ID HERE",loginHandler);
To find out what data this callback function will receive, look up the FacebookDesktop init() method in the SDK documentation as outlined in the following steps.
init() method of the FacebookDesktop class in the com.facebook.graph package (see Figure 21).
The callback function must have two arguments (an object that will be passed to it if the initialization succeeds, and a second object if it fails) and returns nothing.
loginHandler() that has no return value and two arguments of type Object.protected function loginHandler(success:Object,fail:Object):void
{
}
The first time a user accesses the application, a shared object and an access token do not exist and the user will need to log in to Facebook. To accomplish this, you use the FacebookDesktop login() method, which creates a new operating system window that displays the Facebook login page. A popup window is necessary for security reasons so the user knows they are logging into Facebook.
Your Button code should appear as shown here:
<s:Button label.loggedout="Log out" label.loggedout="Log in" includeIn="loggedout" right="10" top="10" click.loggedout="loginoutBtn_clickHandler(event)"/>
loginoutBtn_clickHandler() function to login() and remove the event parameter.The Button code should appear as shown here:
<s:Button id="loginoutBtn" click.loggedout="login()" .../>
... and the function as shown here:
protected function login():void
{
}
login() method of the com.facebook.graph.FacebookDesktop class. It has one required argument, a callback function that receives two Objects—the first if login succeeds and the second if login fails. It also has an optional argument for requesting extended permissions that you will work with later in this tutorial.login() function, call the static login() method of the FacebookDesktop class and pass to it a reference to the existing loginHandler function.protected function login():void
{
FacebookDesktop.login(loginHandler);
}
Follow these steps:
You have now successfully connected your application to Facebook and established a user session. Next, you are going to look at the data being passed back from Facebook and see the properties of the logged in user.
loginHandler() function by clicking in the gutter to the left of one of the line numbers inside the function (see Figure 26).
Note: If you get a message that you do not have the Debug version of Flash Player installed, go to Flash Player Downloads on Adobe.com and download the latest debug installer for your browser. Close your browser and then run the installer.
At this point, your application launches and focus may immediately return to Flash Builder.
You are now in the Debugging perspective, which shows different views of information (see Figure 28).
access_token, expireDate, uid, user and more (see Figure 29).
id, name, gender, and more (see Figure 29 above).
loginHandler() function, create conditional logic checking to see if the user successfully logged into Facebook by seeing if the success argument exists (is not null).if(success){
}
currentState property of the application to loggedin.if(success){
currentState="loggedin";
}
If you see a login button, log in, and then make sure you see the logout button in the loggedin application state.
Next, use the the Facebook logout() method to add logout functionality.
click event in the loggedin state and specify a function logout() to be the event handler.<s:Button id="loginoutBtn" click.loggedout="login()" click.loggedin="logout" .../>
logout() that has no arguments and returns nothing.protected function logout():void
{
}
logout() method of the FacebookDesktop class. It has no required arguments and returns nothing.logout() function, call the static logout() method of the FacebookDesktop class and set the application's currentState property to loggedout.protected function logout():void
{
FacebookDesktop.logout();
currentState="loggedout";
}
Now that you have successfully authorized your application and created a user session, you are going to display information about the logged in user.
When a Facebook user authorizes your application, your application gets access to the user's Facebook ID. By default, your application can access all public data in a user's profile, including her name, profile picture, gender, and friends. If your application needs to access other parts of the user's profile that may be private (like birthdays, photos, events, hometown, and so on), or if your application needs to publish content to Facebook on a user's behalf, your application must request extended permissions.
In this section, you start out by displaying basic user info that requires no extended permission including the user's name and the user's profile picture. After, you learn how to request extended permissions to display the user's birthday and status messages.
In the last section, you used the Flash Builder debugger to look at a user's public data returned from Facebook. Start by displaying some of this information in the application.
if block of the loginHandler() function, set the text property of the nameLbl object to session.user.name.if(success){
currentState="loggedin";
nameLbl.text=success.user.name;
}
To retrieve a user's profile picture, you use the static getImageUrl() method of the FacebookDesktop class.
getImageUrl() method of the FacebookDesktop class. It has one required argument (the id of the user), one optional argument (the size of the image to display from Facebook: square, small, or large), and returns a String (the image URL).loginHandler() function, set the source property of the userImg Image control equal to the return value from a call to the FacebookDesktop getImageUrl() method. Pass to the method the user ID, success.uid, and the type of image desired, "small".if(success){
currentState="loggedin";
nameLbl.text=success.user.name;
userImg.source=FacebookDesktop.getImageUrl(success.uid,"small");
}
To retrieve and display any information about a user besides what is included in their basic public profile, you must first get permission from the user using extended permissions. You can request these permissions when the user logs in or you can request them on demand when they are needed. In this section, you request permission to retrieve the user's birthday when the user logs in.
login() method of the FacebookDesktop class. It has a second optional argument that you set equal to an array of extended permissions to ask the user for once she is logged in.login() function in the SDK documentation, click http://developers.facebook.com/docs/authentication/permissions. A new browser tab or window is opened and the Facebook documentation for extended permissions is displayed.
login() function, add a second argument that is an array containing one item, the string user_birthday.protected function login():void
{
FacebookDesktop.login(loginHandler,["user_birthday"]);
If the application had not already been authorized (that is, if this was the first time the user was logging in to this application), she would receive a single Request for Permission dialog box (see Figure 40).
If you want to test this behavior, you can de-authorize the application on Facebook.com and then run and log in to your application again. To de-authorize the application, go to Facebook.com in a browser window; log in; navigate to Account > Account Settings; select Applications on the left, click the x to the right of the YourLastName User Status AIR application; in the dialog box that opens, click Remove; and in the final dialog box, click Okay. If you do this, make sure you re-authorize the application before continuing to the next step.
loginHandler() function and debug the application.
if block of the loginHandler() function, set the text property of the birthdayLbl object to session.user.birthday.if(success){
currentState="loggedin";
nameLbl.text=success.user.name;
userImg.source=FacebookDesktop.getImageUrl(success.uid,"small");
birthdayLbl.text=success.user.birthday;
}
Next, you are going to retrieve, display, and post user status messages.
Start by updating your status on the Facebook web site so you have a message to retrieve and display.
To make calls to the Facebook Graph API to get or set additional user information (including status messages), you use the FacebookDesktop api() method.
api() method of the FacebookDesktop class. It has two required arguments: the Facebook Graph API method to call and a callback function. The callback function receives two objects, the first is the call is successful, the second if it fails.api() method. The Facebook Developer documentation for the Graph API opens in a new browser tab or window.
api() method, you pass as a first argument (the method to call on the Graph API) the string "/me/statuses". If you wanted to get photo data, you would pass "/me/photos".
The info for the statuses connection here also tell you that to make this connection you must have the read_stream permission. Remember, you can look at a list of all the extended permissions on the Facebook Developer documentation for extended permissions page.
Next, request user permissions to retrieve status messages and then retrieve and display the messages in your application.
if block of the loginHandler() function, call the FacebookDesktop api() method and pass the Graph API method to call "/me/statuses" and a new callback function getStatusHandler().if(success){
currentState="loggedin";
nameLbl.text=success.user.name;
userImg.source=FacebookDesktop.getImageUrl(success.uid,"small");
birthdayLbl.text=success.user.birthday;
FacebookDesktop.api("/me/statuses",getStatusHandler);
}
getStatusHandler() with two arguments of type Objects and no return value.protected function getStatusHandler(result:Object, fail:Object):void
{
}
getStatusHandler() and debug the application.loginHandler() to the one inside getStatusHandler() (see Figure 46).
result argument is populated but it has a length of zero (see Figure 47). No status messages were returned because we did not request the necessary extended permission from the user yet.
login() function, change the second argument to an array with two items, the strings "user_birthday" and "read_stream".protected function login():void
{
FacebookDesktop.login(loginHandler,["user_birthday","read_stream"]);
}
Note: You can also use the FacebookDesktop requestExtendedPermissions() method to request additional permissions after the user has already logged in to the application.
loginHandler() to the one inside getStatusHandler().updated_time property in the array. The latest message is first in the array.
text property.getStatusHandler(), set the text property of statusLbl to the message property of the first status message in the array of returned status messages.protected function getStatusHandler(result:Object, fail:Object):void
{
statusLbl.text=result[0].message;
}
Next, post messages from the Flex application to Facebook. Just as for retrieveing messages, you need to request an appropriate extended permission and then use the FacebookDesktop api() method, but in this case, you send instead of receive data.
click event handler of submitPost().<s:FormItem label="Post status">
<s:layout>
<s:HorizontalLayout/>
</s:layout>
<s:TextInput id="statusInput"/>
<s:Button label="Submit" click="submitPost()"/>
</s:FormItem>
submitPost() that has no arguments and no return value.protected function submitPost():void
{
}
message property.
login() method, add the publish_stream permission to the array of requested permissions.protected function login():void
{
FacebookDesktop.login(loginHandler,["user_birthday","read_stream", "publish_stream"]);
}
Note: You can also use the FacebookDesktop requestExtendedPermissions() method to request permissions at runtime sometime after the user has logged in.
submitPost(), call the static api() method of FacebookDesktop and pass to it the method to call, "/me/feed"; a callback function, submitPostHandler; an object containing the data to send to the method; and a string specifying the request type, "POST" (not the default "GET") because you are sending data to Facebook.For the data to send to the method, create an object with a property called message and set it equal to the value specified in the statusInput TextInput control: {message:statusInput.text}.
FacebookDesktop.api("/me/feed",submitPostHandler,{message:statusInput.text}, "POST");
submitPostHandler(), with two arguments of type Object and no return value.protected function submitPostHandler(result:Object,fail:Object):void
{
}
submitPostHandler(), set the statusInput object's text property to an empty string.statusInput.text="";
postStatusHandler(), retrieve the statuses again.Note: Instead of making a call to Facebook here, you could also just set statusLbl.text to statusInput.text.
protected function submitPostHandler(result:Object,fail:Object):void
{
statusInput.text="";
FacebookDesktop.api("/me/statuses",getStatusHandler);
}
Finish up by skinning your buttons so they look like the buttons provided by Facebook for use in HTML pages.
source property to the fblogin.gif image in the images folder. Use the Embed compiler directive to embed the image in the SWF.<?xml version="1.0" encoding="utf-8"?>
<s:Skin xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx">
<fx:Metadata>
[HostComponent("spark.components.Button")]
</fx:Metadata>
<s:states>
<s:State name="disabled" />
<s:State name="down" />
<s:State name="over" />
<s:State name="up" />
</s:states>
<s:BitmapImage source="@Embed('images/fblogin.gif')"/>
</s:Skin>
skinClass so it is set appropriately for each state.<s:Button id="loginoutBtn" right="10" top="10"
label="Log out" label.loggedout="Log in"
skinClass.loggedin="skins.FBLogoutButtonSkin"
skinClass.loggedout="skins.FBLoginButtonSkin"
click.loggedin="logout()"
click.loggedout="login()"/>
In Part 1 of this tutorial series, you used Flash Builder and the Adobe ActionScript 3 SDK for Facebook Platform to build a local desktop application that has Facebook login and logout functionality; requests extended permissions from the user; retrieves and displays user information; and retrieves, displays, and posts new status messages.
There are many other ways to interact with Facebook, including methods to modify your profile; get photos and albums, upload photos, and create albums; send and get notifications; create, edit, get, and delete notes and events; get friends and their info; and more. For details and examples of these types of interaction with Facebook, see the Facebook Graph API documentation and sample code.
To learn more about creating and customizing Flex applications, see the Flex documentation and the Adobe Flex Developer Center. To learn more about creating and customizing AIR applications, see the AIR documentation and the Adobe AIR Developer Center.
To package, deploy, and distribute the application you built in this tutorial as a desktop application, continue with Part 2 of this tutorial series, Package and deploy as a desktop application.
To deploy the application as an external web application, continue with Part 3 of this tutorial series, Modify and deploy as a web application.
To deploy the application as a web application on Facebook.com, continue on to Part 4 of the tutorial series, Part 4: Modify and deploy on Facebook.com.