This is a tutorial on integrating Facebook API in your Flex Mobile app using Adobe AIR to publish it to mobile devices.
In order to start with this, you would first need to download the AS3 version of Facebook API from: http://code.google.com/p/facebook-actionscript-api/
After downloading the library, we need to create an App on Facebook.
In order to build a Facebook App, we need to create one under Facebook developer. For this, go to http://developers.facebook.com/ and go to Apps. Once there, select option to Create New App and fill the required details. Once the application has been setup, we would need the App ID/API Key of the app just created. We will use this in our project.
Next we need to setup a new Flex Mobile Project. Open Flash Builder and create a new Flex Mobile Project. For the current tutorial, I have used a View Based Application template. You can use any one you want according to the requirement of your project.
Once created, we will be presented with the FirstView of the application which Flash Builder creates automatically for us.
For the design part, I have created a simple UI which has a login button, a label which will display the name of the logged in person, a text area which we will use to post content on Facebook Wall and a Post on Wall. This all has been added into a SkinnableContainer. A SkinnableContainer is a lightweight component which is optimized for Mobile devices.
Setting up the required variables in the App:
[cc lang=”actionscript3″]
//Your App Id as created on Facebook
private const APP_ID:String = “YOUR_APP_ID”;
//App origin URL
private const FACEBOOK_APP_ORIGIN:String = “http://rjdesignz.com”;
//Permissions Array
private const PERMISSIONS:Array = [“publish_stream”];
//SatgeWebView to render Facebook login
private var facebookWebView:StageWebView;
private var accessToken:String = “”;
[/cc]
Here in the above code, we are creating the variables/constants we will be using in our application.
- We create a constant which will store the Application Id we got from Facebook Developer after creating the app.
- Facebook App Origin which will be used as a point for the app to be used for cookies. We are using this because there are issues while loggin out of the app. This issue has been reported on the Google Code for the API and is still under consideration.
- The permissions are app will require.
- A StageWebView to render the login from Facebook.
- accessToken which we will be using in subsequent API calls.
Initializing the Facebook Object:
[cc lang=”actionscript3″]
private function init():void
{
//Initialize Facebook library
FacebookMobile.init(APP_ID, onFacebookInit);
}
private function onFacebookInit(result:Object, fail:Object):void
{
busyInd.visible = false;
fbLoginBtn.enabled = true;
//Session already exists
if(result)
{
accessToken = result.accessToken;
setPostMessage(result.user);
}
}
[/cc]
In the creationComplete event, we call the static method init of the FacebookMobile class and pass two parameters: one being the application id and other being the callback function for the result. In the callback method, we receive two parameters. One is the success object and the other being failure. If success object is not null, we have a valid login and set the access token here. We also set here the username as received from the response.
Login Clicked by user:
[cc lang=”actionscript3″]
private function onFBLoginClick(e:MouseEvent):void
{
busyInd.visible = true;
if(fbLoginBtn.label == “Login to Facebook”)
{
facebookWebView = new StageWebView();
facebookWebView.viewPort = new Rectangle(0, navigator.actionBar.height, width, height);
FacebookMobile.login(onLogin, stage, PERMISSIONS,facebookWebView);
}
else if(fbLoginBtn.label == “Logout”)
{
FacebookMobile.logout(onLogout, FACEBOOK_APP_ORIGIN);
}
}
[/cc]
Next we write code to handle login clicked by user. Here we create a StageWebView object and set the area for it equal to the app area, excluding the top action bar. We call the login method of the FacebookMobile class and pass as parameters the: callback function, stage, permissions and the web view created above. Once we run the app, FacebookMobile will use this webview to render the login form for the user and automatically get removed once login is successful.
Same as in Facebook init response, we save the access token as received after successful login.
Posting on user’s wall:
[cc lang=”actionscript3″]
private function onPostOnWallClick(e:MouseEvent):void
{
busyInd.visible = true;
var params:Object = {};
params.message = postTxtArea.text;
params.action_token = accessToken;
FacebookMobile.api(“/me/feed”, onPostStatus, params, “POST”);
}
[/cc]
We create an object where we set the message property, the message to be posted on user’s wall and the action_token property as the access token we have with us. We call the api method of the FacebookMobile library and pass as parameters: the action method, the callback function, parameters object and method type. Once a successful post is made on the wall, we get a result object else a failure object in the callback function.
This was a quick overview on starting up with the FacebookMobile API in Flex Mobile project. You can definitely extend it further in your project to get more user data, get wall posts, post on wall, post on friend’s wall etc. You can read more about this on Facebook Developer’s Graph API documentation.
You can download the code for the above project from here.
Recommended readings for Flash/Flex/AIR Mobile Applications:
- iOS Development with Flash: Your visual blueprint for developing Apple apps
- Flash Development for Android Cookbook
- Android Development with Flash: Your visual blueprint for developing mobile apps
- Flash Mobile: Setting up Flash CS5 for Android Development: Setting up Flash CS5 for Android Development
- Flash Mobile: Rapid Android Development in Flash CS5: Rapid Android Development in Flash CS5
Hi Rahul,
Cool to find this post. I am facing a strange problem.
I am using Flash builder 4.6 & graph API 1.8.1
// ************ FIRES ON FLEX AIR APPLICATION COMPLETE EVENT***********
private function mainAppCreationComplete(evt:FlexEvent):void {
initializeFBApi();
}
private function initializeFBApi():void {
Facebook.init(“XXXXXXXXXXXXX”,onFBInit);
}
private function onFBInit(result:Object, fail:Object):void {
if(result){
Alert.show(“USER NAME IS: “+result.user.name);
birthdayLbl.text=success.user.birthday;
} if(fail) {
Alert.show(“FAILURE”);
}
}
// *********** FIRES ON FLEX LOGIN BUTTON CLICK
private function onFacebookLoginButtonClick(evt:Event):void {
Alert.show(“FACEBOOK LOGIN clicked”);
Facebook.login(onFBInit,_permissions);
}
First time the login box opens up allowing to enter emailID and password, but the next time the box opens
and disappears.
NEITHER OF THE TWO ALERTS POPS-UP
The alert in onFBInit does not comes… where exactly am i doing wrong?
Thanks
It doesn’t comes out the second time because of the cookies are not cleared and it uses the previous session. So as soon as the login window opens, it gets existing session and goes off quickly. This is a quite old and frequently discussed issue: http://code.google.com/p/facebook-actionscript-api/issues/detail?id=217
See if this link helps: http://www.monday8am.com/en/2012/07/09/facebook-close-session/
Thank Rahul for making something so hard look so easy 🙂
A question that baffles me: we are not using the API Secret / Key anywhere!
Isn’t that a potential security hole?
I was surprised to see the secret only used in the .php in the examples folder (supposedly so nobody steals it).
Can you give me some example for doing it in Air desktop application
Hi, Thanks for the great post. Any idea how do I add photos or videos to this same post?
Thanks in advance.
Have an idea about posting photos:
– Make sure you use the correct method for posting photos, i.e., “/me/photos”
– You need to pass an object as parameter in which you need to have the image property as the bytearray of image to be posted.
You can search on Adobe Devnet or download the examples with AS3 Graph API. Both ways you’ll find examples on how to use it in desktop.
/me/photos looks like the way to go. Thanks again
I have got below error message after login on screen.
{
“error”: {
“message”: “Error validating application. Invalid application ID.”,
“type”: “OAuthException”,
“code”: 101
}
}
I’m a newbie on this.. please help me out..
Thanks & regards
Joyeta
Great post, exactly what I was looking for. Thanks mate!
what do we have to enter in the field “Class Name” in the face book developer page?
I get this error on initialising the api
{“error”:{“message”:”An active access token must be used to query information about the current user.”,”type”:”OAuthException”,”code”:2500}}
can you please tell me why?