Adobe
Products
Acrobat
Creative Cloud
Creative Suite
Digital Marketing Suite
Digital Publishing Suite
Elements
Photoshop
Touch Apps
Student and Teacher Editions
More products
Solutions
Digital marketing
Digital media
Education
Financial services
Government
Web Experience Management
More solutions
Learning Help Downloads Company
Buy
Home use for personal and home office
Education for students, educators, and staff
Business for small and medium businesses
Licensing programs for businesses, schools, and government
Special offers
Search
 
Info Sign in
Welcome,
My cart
My orders My Adobe
My Adobe
My orders
My information
My preferences
My products and services
Sign out
Why sign in? Sign in to manage your account and access trial downloads, product extensions, community areas, and more.
Adobe
Products Sections Buy   Search  
Solutions Company
Help Learning
Sign in Sign out My orders My Adobe
Preorder Estimated Availability Date. Your credit card will not be charged until the product is shipped. Estimated availability date is subject to change. Preorder Estimated Availability Date. Your credit card will not be charged until the product is ready to download. Estimated availability date is subject to change.
Qty:
Purchase requires verification of academic eligibility
Subtotal
Review and Checkout
Adobe Developer Connection / Facebook /

Create your first Flex and Facebook application – Part 1: Build and test locally

by Jeanette Stallons

Jeanette Stallons
  • stallons.com

Content

  • Register an application with Facebook
  • Create a simple Flex desktop application
  • Add Facebook login and logout
  • Get and display Facebook user info
  • Get and post Facebook status messages
  • Skin the login and logout buttons

Modified

26 September 2011

Page tools

Share on Facebook
Share on Twitter
Share on LinkedIn
Bookmark
Print
application desktop Facebook Flash Builder 4 social networking

Requirements

Prerequisite knowledge

  • Basic knowledge of web technologies and object-oriented programming principles is helpful.
  • Flash and Facebook technology overview
  • Flash and Facebook architecture overview

 

You also need:

- A Facebook account: Sign up

- ActionScript 3 SDK for Facebook Platform

User level

Beginning

Required products

  • Flash Builder (Download trial)

Sample files

  • flex45_fbgraph_assets.zip
  • flex45_fbgraph_pt1_endproject.zip

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:

  • Sign up with Facebook (if you are not already).
  • Add the Facebook Developer application to your profile and bookmark it for easy access (if you have not already).
  • Register a Facebook application to get an application ID that is used along with user information to get an access token to make calls to Facebook.
  • Create a Flex desktop application with Flash Builder that has two states.
  • Add Facebook login and logout functionality.
  • Retrieve and display information about the logged in Facebook user.
  • Use extended permissions.
  • Retrieve, display, and post status messages.
  • Skin buttons to look like Facebook buttons.

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.

Register an application with Facebook

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.

Sign up with Facebook

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.

  1. Open a browser and go to the Facebook website.
  2. In the Sign Up form on the right side of the page, enter your name, email, password and other personal info, and then click the Sign Up button (see Figure 1).
Sign up with Facebook.
Figure 1. Sign up with Facebook.
  1. In the Security Check text box, enter the characters you see in the image and then click the Sign Up button.
  2. Open your email and wait until you receive a confirmation email from Facebook. (Be patient, this may take up to 15 minutes.)
  3. When you receive the email from Facebook, click the confirmation link. This takes you to the Facebook website where you can step through the rest of the setup process.
  4. Complete the setup process. Be sure to upload an image for your profile so you can later retrieve and display it in the Flex application.

Create a new Facebook application

In order to make calls to Facebook from an application, you must first use the Facebook Developer application to set up the new application.

  1. In a browser, go to the Facebook Developer application at http://www.facebook.com/developers/.
  2. In the Request for Permission dialog box that appears, click Allow (see Figure 2).
Allow the Developer application to access your basic information.
Figure 2. Allow the Developer application to access your basic information.
  1. If you have not already done so, download and unzip flex45_fbgraph_assets.zip. This ZIP contains images you can use when creating your Facebook application.
  2. In the Facebook Developer application by click the Create New App button (see Figure 3).
Create a new application.
Figure 3. Create a new application.
  1. Enter the application name, YourLastName User Status AIR, agree to the terms of service, and click Continue (see Figure 4). You are prefacing the name of the application with your last name so the application name is unique.
Create a Facebook application.
Figure 4. Create a Facebook application.
  1. Follow the instructions on the Security Check page and click Submit.
  2. Note: If you get a message to verify your account, click the mobile phone or credit card link and follow the instructions.

  3. On the Settings > Basic page for YourLastName User Status AIR, note the Application ID assigned to your application (see Figure 5). You will need to return here later to copy this value and use it in your Flex application.
Look at the application ID.
Figure 5. Look at the application ID.
  1. Click the Edit icon link (see Figure 5).
  2. In the Upload an Icon dialog box, browse to the fb_status_app_icon16.png image located in the images folder of the flex4_fbgraph_assets.zip, and click open.
  3. Mouse over the default application logo (see Figure 5), click the Edit link and upload the fb_status_app_icon75.png image located in the images folder of the flex45_fbgraph_assets.zip.
  4. Click the Save Changes button at the bottom of the page.

Create a simple Flex desktop application

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.

Create a Flash Builder desktop project

The first step is to create a Flash Builder project for the application.

  1. Unless you have done so already, download and install Flash Builder.
  2. Open Flash Builder.
  3. Select File > New > Flex Project.
  4. In the New Flex Project dialog box, enter FacebookUserStatusAIR as the project name (see Figure 6).
Create a Flex project.
Figure 6. Create a Flex project.
  1. Leave the default location selected or navigate to a new location where you would like your project folder created.
  2. For the Application type, select Desktop application (see Figure 6).
  3. Click Finish. The project will be created and you should see a file called FacebookUserStatusAIR.mxml displayed.

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.

Add a login button

Next, add a login button to the application and run the application.

  1. Click the Design button located in the top of the code window.
  2. From the Components panel, drag out a Button instance and drop it in the upper right corner of the Design area (see Figure 7).
Build the application in Design view.
Figure 7. Build the application in Design view.
  1. With the button still selected, set the Label field in the Properties view to Log in (see Figure 8).
Set the button's label property.
Figure 8. Set the button's label property.
  1. Click the Source button at the top of the code window and look at the generated code. You should see a new Button instance with some position values.
<s:Button x="200" y="35" label="Log in"/>
  1. To compile and test the application, click the green Run button on the main menu bar or select Run > Run FacebookUserStatusAIR.
  2. 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.

Run the application with the AIR Debug Launcher.
Figure 9. Run the application with the AIR Debug Launcher.
  1. Close the ADL window
  2. Return to FacebookUserStatusAIR.mxml in Flash Builder.

Create login and logout states

Next, create two application states: a login state that displays a login button and a logout state that displays a logout button.

  1. Click the Design button at the top of the code window.
  2. In the States view, click the New State button (see Figure 10).
Create a new state.
Figure 10. Create a new state.
  1. In the New State dialog box, enter a name of loggedin, select Duplicate of <State 1>, and click OK (see Figure 11).
Create a new loggedin state.
Figure 11. Create a new loggedin state.
  1. In the States view, select State1 and then click the Edit State Properties button (see Figure 12).
Edit a state.
Figure 12. Edit a state.
  1. In the Edit State Properties dialog box, change the name from State1 to loggedout and click OK. With the loggedout state selected in the States view, you should see your login button in the Design area.
  2. Select the button and scroll down to the bottom of the Properties view and under Constraints, set top and right constraints of 10 pixels (see Figure 13). The button will now always appear 10 pixels from the top and 10 pixels from the right of the container it is displayed in (in this case, the WindowedApplication container).
Set button constraints.
Figure 13. Set button constraints.
  1. Right-click the button and select Apply Current Properties to All States.
  2. In the States view, click loggedin.
  3. Change the button's label property in this state to Log out.
  4. Switch back and forth between the two states.
  5. Run the application. You should see the loggedout state (see Figure 14), but have no way to switch to the loggedin state.
Run the application and see the loggedout state.
Figure 14. Run the application and see the loggedout state.

Add Facebook login and logout

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.

Add the Adobe ActionScript 3 SDK for Facebook Platform to your project

The first step is to download the Adobe ActionScript 3 SDK for Facebook Platform and make its classes available to your project.

  1. In a browser, go to the Google repository for the Adobe ActionScript 3 SDK for Facebook Platform.
  2. Click the Downloads tab.
  3. Click the GraphAPI_Desktop_1_7.swc (or later) file and save the file to your computer.
  4. Drag this SWC file and drop it in the libs folder of your FacebookUserStatusAIR Flex project (see Figure 15).
Add the Adobe ActionScript 3 SDK for Facebook Platform to your Flex project.
Figure 15. Add the Adobe ActionScript 3 SDK for Facebook Platform to your Flex 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.

Initialize the application

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.

  1. Return to FacebookUserStatusAIR.mxml and switch to Source mode.
  2. Register to listen for the WindowedApplication's creationComplete event and generate a creationComplete handler (see Figure 16).
Generate a creationComplete handler.
Figure 16. Generate a creationComplete handler.

    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>
  1. Inside the function, call the static 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.
Select FacebookDesktop from the Code Assist pop-up.
Figure 17. Select FacebookDesktop from the Code Assist pop-up.

    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.

  1. Look at the code-hinting for the init() method; it has two required arguments. You must pass an application ID and a callback function (see Figure 18).
Locate arguments for the FacebookDesktop init() method.
Figure 18. Locate arguments for the FacebookDesktop init() method.
  1. Retrieve your application ID from the Facebook Developer application: return to the Facebook Developer application in a browser window, and click the link for YourLastName User Status AIR.
  1. Copy the Application ID (see Figure 19).
Copy your application ID.
Figure 19. Copy your application ID.
  1. Return to Flash Builder and pass to the FacebookDesktop 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.

  1. In a browser window, naviagte to the SDK's home page on the Google Code repository and click the docs link on the Project Home (see Figure 20). Bookmark this page in your browser so you can return to it later.
Browse to the SDK's documentation.
Figure 20. Browse to the SDK's documentation.
  1. Navigate to the init() method of the FacebookDesktop class in the com.facebook.graph package (see Figure 21).
Look up the FacebookDesktop init() documentation.
Figure 21. Look up the FacebookDesktop init() documentation.

    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.

  1. Return to FacebookuserStatusAIR.mxml in Flash Builder.
  2. Inside the Script block, create a protected function loginHandler() that has no return value and two arguments of type Object.
protected function loginHandler(success:Object,fail:Object):void { }

Add login functionality

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.

  1. In Design mode, select the loggedout state and give the button an id of loginoutBtn.
  2. Right-click the button and select Generate Click Handler.
  3. 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)"/>
  1. Change the name of the loginoutBtn_clickHandler() function to login() and remove the event parameter.
  2. 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 { }
  1. Return to the SDK documentation and look up the 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.
  2. Return to Flash Builder and inside the 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); }

Log in and authorize the application

Follow these steps:

  1. Run the application and click the login button. You should get a Facebook Login dialog box in a second operating system window (see Figure 22).
Get a Facebook Login window.
Figure 22. Get a Facebook Login window.
  1. Enter your email and password and click the Log in button. You should get a Request for Permission dialog box (see Figure 23).
Get Request for Permission window.
Figure 23. Get Request for Permission window.
  1. Click the Allow button. The second operating window should close, but you should see no change in the application's user interface. You will change this in the next section to provide feedback to the user so she knows when she has successfully logged in.
  2. Close the application.
  3. In a browser window, return to Facebook.com, log in if necessary, and select Home > Account Settings (see Figure 24).
Go to your Account Settings on Facebook.
Figure 24. Go to your Account Settings on Facebook.
  1. In the navigation list on the left, select Apps.
  2.  Locate your application YourLastName User Status AIR in the list of authorized applications (see Figure 25).
Confirm your application has been authorized.
Figure 25. Confirm your application has been authorized.

Look at the data returned from Facebook

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.

  1. Add a breakpoint inside theloginHandler() function by clicking in the gutter to the left of one of the line numbers inside the function (see Figure 26).
Add a breakpoint.
Figure 26. Add a breakpoint.
  1. To debug the application, click the bug button in the main menu bar (see Figure 27) or select Run > Debug FacebookUserStatusAIR.
  2. 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.

Debug the application.
Figure 27. Debug the application.

    At this point, your application launches and focus may immediately return to Flash Builder.

  1. If focus is not immediately returned to Flash Builder, click the login button in your application, and log in. Now, focus should be returned to Flash Builder.
  2. If you get a dialog box in Flash Builder asking you to switch to the Debugging perspective, select the check box to Remember my decision and then click the Yes button.
  3. You are now in the Debugging perspective, which shows different views of information (see Figure 28).

Use the debugger to look at the results from Facebook.
Figure 28. Use the debugger to look at the results from Facebook.
  1. Double-click the Variables tab in the upper right corner of the window to make it full size in Flash Builder.
  2. Drill down into the success object by clicking the arrow to the left of it and examine its properties. It is of type FacebookSession and has properties access_token, expireDate, uid, user and more (see Figure 29).
Examine the results returned from Facebook.
Figure 29. Examine the results returned from Facebook.
  1. Drill down into the user Object and look at its properties, which include id, name, gender, and more (see Figure 29 above).
  2. Double-click the Variables tab again to return it to its initial size.
  3. Click one of the square red stop buttons to stop the debugger.
  4. Return to the Development perspective by clicking the Flash button in the upper-right corner of Flash Builder (see Figure 30). If you do not see this button, drag the tabs to the left to make them larger until you see it, or click the Add button and select it from the pop-up menu.
Switch to the Flex Development perspective.
Figure 30. Switch to the Flex Development perspective.
  1. Inside the 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){ }
  1. If the user is logged in successfully, change the currentState property of the application to loggedin.
if(success){ currentState="loggedin"; }
  1. Run the application. If you have already successfully logged into Facebook recently, you will not get the login button and will instead see the logout button (see Figure 31). The FacebookDesktop class used the shared object to automatically log you in to the application and switched to its loggedin state.
  2. If you see a login button, log in, and then make sure you see the logout button in the loggedin application state.

See the loggedin state when you successfully log in.
Figure 31. See the loggedin state when you successfully log in.
  1. Close the application.

Add logout functionality

Next, use the the Facebook logout() method to add logout functionality.

  1. In Flash Builder Source mode, locate the button and register to listen for its 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" .../>
  1. Inside the Script block, create a function logout() that has no arguments and returns nothing.
protected function logout():void { }
  1. In a browser window, return to the SDK documentation and look up the logout() method of the FacebookDesktop class. It has no required arguments and returns nothing.
  2. Return to Flash Builder and inside the 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"; }
  1. Run the application, log in if necessary, and then log out by clicking the logout button. You should see the login button again.
  2. Click the login button. You should get the Facebook Login window again.
  3. Log in and then close the application.

Get and display Facebook user info

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.

Display basic user profile info

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.

  1. In Flash Builder, switch to Design mode and select the loggedin state.
  2. From the Layout section of the Components view, drag out a Form container and drop it in the Design area.
  3. In the Insert Form dialog box, leave the width and height as <fit to content> and click OK.
  4. With the Form container selected, go the Constraints section of the Properties view and constrain it to always be 70 pixels from the left and 10 from the top (see Figure 32).
Add a Form container with constraints.
Figure 32. Add a Form container with constraints.
  1. From the Controls section of the Components view, drag out a Label control and drop it in the Form container in the Design area.
  2. Double-click the Label text on the left and change it to User.
  3. Select the Label control on the right and in the Properties view, assign an ID of nameLbl and delete the Text value (see Figure 33).
Add a Label control to the Form container.
Figure 33. Add a Label control to the Form container.
  1. Switch to Source mode and inside the 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; }
  1. Run the application and if necessary, log in to Facebook. You should see your name successfully displayed in the application (see Figure 34).
Display basic user info.
Figure 34. Display basic user info.

Display a user's profile picture

To retrieve a user's profile picture, you use the static getImageUrl() method of the FacebookDesktop class.

  1. In Flash Builder, switch to Design mode and select the loggedin state.
  2. From the Controls section of the Components view, drag out an Image control and drop it to the left of the Form container.
  3. Select the Image control and in the Properties view, assign an ID of userImg, a width of 50, and constraints of 10 pixels from the left and 10 from the top (see Figure 35).
Set properties for an Image control.
Figure 35. Set properties for an Image control.
  1. In a browser window, return to the SDK documentation and look up the 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).
  2. In Flash Builder, switch to Source mode and inside the if block of the 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"); }
  1. Run the application and if necessary, log in to Facebook. You should see your profile picture successfully displayed in the application (see Figure 36).
Display a user's profile picture.
Figure 36. Display a user's profile picture.
  1. Close the application.

Display info that requires extended permissions

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.

  1. In Flash Builder, switch to Design mode and select the loggedin state.
  2. From the Controls section of the Components view, drag out a Label control and drop it after the other Label inside the Form container.
  3. In the new FormItem instance, double-click its Label text on the left and change it to Birthday.
  4. In the same FormItem instance, select its Label control on the right and in the Properties view, assign an ID of birthdayLbl and delete its Text value (see Figure 37).
Add another Label control to the Form container.
Figure 37. Add another Label control to the Form container.
  1. In a browser window, return to the SDK documentation and look up the 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.
  2. In the See also section for the 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.
  3. Locate the user_birthday permission in the Read Permissions section (see Figure 38).
Look up extended permissions in Facebook API documentation.
Figure 38. Look up extended permissions in Facebook API documentation.
  1. In Flash Builder, switch to Source mode and inside the 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"]);
  1. Run the application and if you are already logged in, log out.
  2. Click the login button, enter your email and password, and click the Log In button. You should get a Request for Permission window requesting the extended permission for birthday information (see Figure 39).
Get the Request for Permission window for extended permissions.
Figure 39. Get the Request for Permission window for extended permissions.
  1. In the Request for Permission window, click the Allow button. You will not see the birthday displayed yet; you will add code for that next.
  2. Close the application.
  3. 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).

Get the Request for Permission window for basic and extended permissions.
Figure 40. Get the Request for Permission window for basic and extended permissions.

    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.

  1. Return to Flash Builder and make sure there is still a breakpoint inside the loginHandler() function and debug the application.
  2. In the Flash Builder Flash Debug perspective, double-click the Variables tab to expand the view and drill down to look at the properties of the user object (see Figure 41). You should now see it has a birthday property.
Locate the new birthday property of the user object.
Figure 41. Locate the new birthday property of the user object.
  1. Return the Variables view to its initial size and stop the debugger.
  2. Switch to the Flash perspective.
  3. Inside the 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; }
  1. Run the application and if necessary, log in to Facebook. You should see your birthday successfully displayed in the application (see Figure 42).
Display user info that requires extended permissions.
Figure 42. Display user info that requires extended permissions.
  1. Close the application.

Get and post Facebook status messages

Next, you are going to retrieve, display, and post user status messages.

Update your status on Facebook.com

Start by updating your status on the Facebook web site so you have a message to retrieve and display.

  1. In a browser window, go to Facebook.com and, if necessary, log in.
  2. In the What's on your mind? input box, enter a new status and click the Post button (see Figure 43).
Post a status message on Facebook.com.
Figure 43. Post a status message on Facebook.com.

Look up info in developer documentation

To make calls to the Facebook Graph API to get or set additional user information (including status messages), you use the FacebookDesktop api() method.

  1. In a browser window, return to the SDK documentation and look up the 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.
  2. Click the http://developers.facebook.com/docs/api link in the See also section for the api() method. The Facebook Developer documentation for the Graph API opens in a new browser tab or window.
  3. Under the Introduction, see that you make connections between objects by making a call to https://graph.facebook.com/ID/CONNECTION_TYPE where different types of objects have different types of connections. In your Flex application, you want to get the status messages for a user.
  4. Scroll down to the bottom of the page and see the list of objects.
  5. Click the User object (see Figure 44). You want to make connections to the logged-in user, a User object.
Look up the User object in the Facebook Graph API reference.
Figure 44. Look up the User object in the Facebook Graph API reference.
  1. Under Connections, locate statuses (see Figure 45). You want to examine the statuses connections for a User object. Thus, you must make a call to https://graph.facebook.com/me/statuses where me refers to the logged-in user. When using the FacebookDesktop 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".
Locate the statuses connection for the User object.
Figure 45. Locate the statuses connection for the User object.

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.

Get and display user status messages

Next, request user permissions to retrieve status messages and then retrieve and display the messages in your application.

  1. Return to Flash Builder.
  2. Inside the 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); }
  1. Inside the Script block, create a new function getStatusHandler() with two arguments of type Objects and no return value.
protected function getStatusHandler(result:Object, fail:Object):void { }
  1. Place a breakpoint inside getStatusHandler() and debug the application.
  2. In Flash Builder, click the Play button to move from the breakpoint inside loginHandler() to the one inside getStatusHandler() (see Figure 46).
Move to the next breakpoint.
Figure 46. Move to the next breakpoint.
  1. In the Variables view, see that the 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.
No status messages are returned yet.
Figure 47. No status messages are returned yet.
  1. Stop the debugger.
  2. Inside the 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"]); }
  1. Run the application and if you are automatically logged into the application, log out. You need to log in again so the new permissions are requested.
  2. Note: You can also use the FacebookDesktop requestExtendedPermissions() method to request additional permissions after the user has already logged in to the application.

  3. Click the login button and log in. You should get a Request Permission dialog box for the new permission (see Figure 48). If this was the first time the user was logging into the application ever, she would see three permissions requested in this window.
Get a Request Permission window for accessing new feed posts.
Figure 48. Get a Request Permission window for accessing new feed posts.
  1. Click the Allow button and then close the application. Next, you will display the latest user status.
  2. Debug the application and in Flash Builder, click the Play button to again move from the breakpoint inside loginHandler() to the one inside getStatusHandler().
  3. In the Variables view, see that the result argument is now populated with an array of Objects (see Figure 49). Each object contains information about a particular post and the objects (messages) are ordered by the updated_time property in the array. The latest message is first in the array.
View returned status messages in the debugger.
Figure 49. View returned status messages in the debugger.
  1. Stop the debugger.
  2. Switch to the Design mode of the Flash perspective.
  3. From the Controls section of the Components view, drag out a Label control and drop it after the other two Labels inside the Form container.
  4. In the new FormItem instance, double-click its Label text on the left and change it to Status.
  5. In the same FormItem instance, select its Label text on the right and in the Properties view, assign an id of statusLb and delete the value of its text property.
  6. Switch to Source mode and inside 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; }
  1. Run the application. You should now see your latest status message in the application (see Figure 50).
Display your latest status message.
Figure 50. Display your latest status message.
  1. Close the application.

Request permission to post messages

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.

  1. In Flash Builder, switch to Design mode and select the loggedin state.
  2. From the Controls section of the Components view, drag out a TextInput control and drop it after the other three Label instances inside the Form container.
  3. In the new FormItem instance, double-click its Label text on the left and change it to Post status.
  4. In the same FormItem instance, select its TextInput control on the right and in the Properties view, assign an ID of statusInput.
  5. Drag out a Button and drop it in the FormItem after the TextInput control. By default, the FormItem lays out its children vertically.
  6. Select the new FormItem and in the Layout section of the Properties view, set its layout to spark.layouts.HorizontalLayout.
  7. Switch to Source mode and inside the last FormItem instance, give the Button control a 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>
  1. Return to Source mode, inside the Script block, create a new function submitPost() that has no arguments and no return value.
protected function submitPost():void { }
  1. In a browser window, return to the Facebook Graph API documentation, click the Post object and scroll down to the Fields section and examine the arguments you can specify when posting a message (see Figure 51). You will set the message property.
Locate arguments for posting messages.
Figure 51. Locate arguments for posting messages.
  1. Return to Flash Builder.
  2. Inside the 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.

  1. Inside 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.
  2. 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");
  1. Inside the Script block, create a function submitPostHandler(), with two arguments of type Object and no return value.
protected function submitPostHandler(result:Object,fail:Object):void { }
  1. Inside submitPostHandler(), set the statusInput object's text property to an empty string.
statusInput.text="";
  1. Still inside postStatusHandler(), retrieve the statuses again.
  2. 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); }
  1. Run the application, and if you are already logged in, log out.
  2. Log in to the application. You should get a Request for Permision window to give the application permission to post to Facebook (see Figure 52).
Grant the application permission to post to the user's wall.
Figure 52. Grant the application permission to post to the user's wall.
  1. Click the Allow button.
  2. Enter a new status message and click Submit (see Figure 53).
Post a new status message.
Figure 53. Post a new status message.
  1. You should now see your latest status message displayed in the application (see Figure 54).
View the message you submitted to Facebook.
Figure 54. View the message you submitted to Facebook.
  1. Close the application.
  2. In a browser window, return to Facebook.com and if necessary, log in. You should see the status message sent from the Flex application displayed (see Figure 55).
View the new message on Facebook.
Figure 55. View the new message on Facebook.

Skin the login and logout buttons

Finish up by skinning your buttons so they look like the buttons provided by Facebook for use in HTML pages.

  1. If you have not already downloaded the assets ZIP, flex45_fbgraph_assets.zip, download and unzip it now. It contains an images folder.
  2. Copy the images folder.
  3. Return to Flash Builder, right-click the src directory of your FacebookUserStatus project, and select Paste. You should now see an images folder inside the src folder.
  4. Switch to Design mode for FacebookUserStatusAIR.mxml.
  5. Select the login button in the loggedout state and in the Style section of the Properties view, click the button next to Skin and select Create Skin (see Figure 56).
Create a new skin class for the login button.
Figure 56. Create a new skin class for the login button.
  1. In the New MXML Skin dialog box, enter a package of skins, a name of  FBLoginButtonSkin, uncheck the Create as copy of check box, and click Finish (see Figure 57).
Specify information for the new MXML skin.
Figure 57. Specify information for the new MXML skin.
  1. In FBLoginButtonSkin.mxml, switch to Source mode.
  2. Inside the Skin tag, add a BitmapImage tag and set its 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>
  1. Save the file.
  2. Go to FacebookUserStatusAIR.mxml in Design mode. You should see your new button skin rendered (see Figure 58).
View the new skin for the login button.
Figure 58. View the new skin for the login button.
  1. Repeat steps 5-10 for the button in the loggedin state and create a skin class called FBLogoutButtonSkin that uses fblogout.gif (see Figure 59).
View the new skin for the logout button.
Figure 59. View the new skin for the logout button.
  1. Switch to Source mode and look at the code for your button.
  2. Change the 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()"/>
  1. Run the application. You should see your new Facebook logout button (see Figure 60).
View the new logout button in your application.
Figure 60. View the new logout button in your application.
  1. Log out. You should see your new login button (see Figure 61).
View the new login button in your application.
Figure 61. View the new login button in your application.

Where to go from here

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.

More Like This

  • Create your first Flex and Facebook application – Part 4: Modify and deploy on Facebook.com
  • Create your first Flex and Facebook application – Part 2: Package and deploy as a desktop application
  • Create your first Flex and Facebook application – Part 3: Modify and deploy as a web application
  • The technologies for building applications on the Flash and Facebook Platforms
  • Build your first Facebook application
  • The architecture of applications built on the Flash and Facebook Platforms
  • Create your first Flex and Facebook application – Introduction

Tutorials and samples

Tutorials

  • Create your first Flex and Facebook application – Part 1
  • Create your first Flex and Facebook application – Introduction
  • Create your first Flex and Facebook application – Part 4

Samples

Products

  • Acrobat
  • Creative Cloud
  • Creative Suite
  • Digital Marketing Suite
  • Digital Publishing Suite
  • Elements
  • Mobile Apps
  • Photoshop
  • Touch Apps
  • Student and Teacher Editions

Solutions

  • Digital marketing
  • Digital media
  • Web Experience Management

Industries

  • Education
  • Financial services
  • Government

Help

  • Product help centers
  • Orders and returns
  • Downloading and installing
  • My Adobe

Learning

  • Adobe Developer Connection
  • Adobe TV
  • Training and certification
  • Forums
  • Design Center

Ways to buy

  • For personal and home office
  • For students, educators, and staff
  • For small and medium businesses
  • For businesses, schools, and government
  • Special offers

Downloads

  • Adobe Reader
  • Adobe Flash Player
  • Adobe AIR
  • Adobe Shockwave Player

Company

  • News room
  • Partner programs
  • Corporate social responsibility
  • Career opportunities
  • Investor Relations
  • Events
  • Legal
  • Security
  • Contact Adobe
Choose your region United States (Change)
Choose your region Close

North America

Europe, Middle East and Africa

Asia Pacific

  • Canada - English
  • Canada - Français
  • Latinoamérica
  • México
  • United States

South America

  • Brasil
  • Africa - English
  • Österreich - Deutsch
  • Belgium - English
  • Belgique - Français
  • België - Nederlands
  • България
  • Hrvatska
  • Česká republika
  • Danmark
  • Eastern Europe - English
  • Eesti
  • Suomi
  • France
  • Deutschland
  • Magyarország
  • Ireland
  • Israel - English
  • ישראל - עברית
  • Italia
  • Latvija
  • Lietuva
  • Luxembourg - Deutsch
  • Luxembourg - English
  • Luxembourg - Français
  • الشرق الأوسط وشمال أفريقيا - اللغة العربية
  • Middle East and North Africa - English
  • Moyen-Orient et Afrique du Nord - Français
  • Nederland
  • Norge
  • Polska
  • Portugal
  • România
  • Россия
  • Srbija
  • Slovensko
  • Slovenija
  • España
  • Sverige
  • Schweiz - Deutsch
  • Suisse - Français
  • Svizzera - Italiano
  • Türkiye
  • Україна
  • United Kingdom
  • Australia
  • 中国
  • 中國香港特別行政區
  • Hong Kong S.A.R. of China
  • India - English
  • 日本
  • 한국
  • New Zealand
  • 台灣

Southeast Asia

  • Includes Indonesia, Malaysia, Philippines, Singapore, Thailand, and Vietnam - English

Copyright © 2012 Adobe Systems Incorporated. All rights reserved.

Terms of Use | Privacy Policy and Cookies (Updated)

Ad Choices

Reviewed by TRUSTe: site privacy statement