Requirements

Prerequisite knowledge

Knowledge of ActionScript and Flex.

Required products
Flash Builder (Download trial)

 

Additional required other products

Facebook ActionScript SDK

User level

Intermediate

Incorporating social services and features like Twitter and Facebook into your mobile application lets you reach more users while instantly adding personalization. It also gives you access to information about your users. You can greet your users with their real names from Facebook or customize the application based on their interests. Hooking into these features also lets you incorporate your application into their social streams by posting to their walls or to their Twitter friends.  I added support for both Facebook and Twitter into my application, 100 Days of Exercise, and wanted to share how I implemented them so you can do the same in your applications.
 

 
Tips when adding social content

Here are some of the tips I’d like to share with you:
 
Dealing with credentials
When adding social content like Facebook and Twitter you’ll be dealing with usernames and passwords for those sites. In nearly all cases, these services won’t allow you to just pass the username/password from your application to authenticate the user. Most services are using a variation of a service called OAuth that exchanges tokens instead of exchanging usernames and passwords directly.
OAuth can be a fairly in-depth topic, but for the purpose of this article, I’ll provide a brief description of how it works. The first thing to do is to register with the service you plan to use, e.g. Facebook. Then you will have a series of token and keys that you pass to the login URL so the service can identify that your application is the one requesting information. Then it has the following flow:
  • User logs in to the service’s website with their credentials.
  • User authorizes the application to access its data.
  • Service redirects the user back to the application with an access token.
  • Application saves access token and accesses the service on the user’s behalf.
This process involves passing a lot of specific URL parameters and following OAuth’s specifications. Shannon Hicks has created a library for ActionScript developers that greatly helps with this process. I’ll show it in more detail in the Twitter Integration section.
 
Using StageWebView
Because our application can’t log in to the service directly, we use StageWebView to provide the ability to log directly in to the service. This keeps the user from typing in a username/password into our application and instead only typing it directly on the site.
 

 
Facebook integration

Adobe has partnered with Facebook to create an SDK specifically for using the Facebook Graph API inside of Flash and Adobe AIR applications. The SDK helps handle all steps of the process including login, asking for specific permissions, and posting to the user’s Facebook wall. In order to get started, go to the Facebook application portal and create a new application. Facebook will provide you with an App ID/API key and an app secret that you can use to integrate Facebook with the SDK.
Once that is set up, download the Facebook ActionScript SDK using the link above, and add it to your project.
 
Connecting to Facebook
For mobile applications you can use the FacebookMobile class which provides the hooks for authenticating and accessing data from a mobile application.  In 100 Days of Exercise, I have an initial view that lets the user connect to Facebook and Twitter. When that view loads, I call the init() method of FacebookMobile passing in my App ID and attach an onLogin event handler.
The events that come from Facebook are a bit more generic than most ActionScript developers will be used to. There is a single event handler that will come with two objects, success or fail. If success is null, then it means the initialization failed. Otherwise, it means it was successful. All of the information about the user is returned as part of the success object if the initialization call was successful.
My code for 100 Days of Exercise just checks to see if we've already connected to Facebook and if so, it will disable the "Connect to Facebook" button and change the label.
 
protected function view1_viewActivateHandler(event:ViewNavigatorEvent):void { saveToDatabase(thisProfile); FacebookMobile.init("261265497221657",onLogin); } private function onLogin(success:Object,fail:Object):void { if(success) { btnFacebook.label = "Facebook Connected"; btnFacebook.enabled = false; } else { trace('facebook error'); } }
 
Logging in to Facebook
The most important part of the entire process is having the user log in. The way the Facebook ActionScript SDK works is that it creates a StageWebView instance with a specific URL that is built using the App ID so it associates that Facebook login with your application. Then the user is logging directly in to Facebook with the URL constructed in the SDK. Facebook works through the authorization process and prompts the user to authorize your application.
This is also where you can request specific permissions. By default, once the user has authorized your application, you can access some basic info about the user. For any elevated permissions, like publishing to the wall, you need to request those specifically. That’s done with the permissions array and is passed to the login() method. This page describes the specific permissions that can be requested.
The login() method can also take a specific viewport for the StageWebview instance. By default the StageWebView takes up the entire screen, but if you need to modify that for any reason (say, to show the ActionBar) you can create a specific viewport rectangle and the FacebookMobile window will use that instead.
Since the init() function has already been called,  the application is registered and you can just go ahead and call the login() function. The Facebook ActionScript SDK will create the correct URL for login so that the login page is associated with the application. Here’s the code for logging in:
 
protected function view1_viewActivateHandler(event:ViewNavigatorEvent):void { facebookWebView = new StageWebView(); var view:Rectangle = new Rectangle(0,actionBar.height,stage.width,stage.height-100-actionBar.height); facebookWebView.viewPort = view; var permissions:Array = ["publish_stream"]; FacebookMobile.login(onLogin,this.stage,permissions,facebookWebView); }
The code above first creates the StageWebView and then creates a Rectangle that takes into account the height of the actionBar so that the FacebookLogin doesn’t cover it up. Then I’ve created an array of permissions, in this case, the only elevated permission I want is to be able to publish to the user’s wall, and finally I use the FacebookMobile class and call the login() method. The login function takes an event handler, onLogin, and then a reference to the parent object of the StageWebView instance, just the stage, and finally any elevated permissions I’m requesting and a specific StageWebView instance.
The onLogin method has the same to inputs, the success/fail objects so I can detect whether the login was successful. This login function will be called only after the entire process is finished, so the user has to log in to Facebook, then authorize the appliation. If they click the “Allow” button, the onLogin method will fire with a success object. If they click “Deny” then it will fire with the fail object.
 
private function onLogin(success:Object,fail:Object):void { if(success) { thisProfile.facebookConnected = true; thisProfile.facebookAccessToken = success.accessToken; } else { trace('error logging into Facebook'); } btnContinue.enabled = true; btnContinue.label = "FINISHED"; }
If the authentication is successful, the success object will include an accessToken. This accessToken is what you use to make any authenticated calls to the Facebook API, including posting to the user’s wall. In 100 Days of Exercise, I store the accessToken in a local database so that I can continue to call the Facebook API without having the user log in again.
 
Posting to the user’s wall
Once the user has authenticated and authorized your application to do what it needs to, you can start calling the Facebook API directly and interacting with content. The full graph API is supported in the SDK, but the one I will show is posting to the Facebook wall.
The SDK uses the api() method to construct the correct Facebook URL and call the API. In this case I’m using the /me/feed API to post to the user’s feed. Here is the full list of APIs you can call. The api() method also takes an event handler for the result of the call as well as a params object. This params object is where you make sure that any parameters the API requires are included (in this case, the message object for the wall post) as well as the access token.
 
var params:Object = new Object() params.message = taStatus.text; params.action_token = thisProfile.facebookAccessToken; FacebookMobile.api("/me/feed",onPostStatus,params,"POST");
The event handler, onPostStatus, is just the same kind of listener that you should be familiar with at this point. It has the same two objects, success and fail, and whichever one is not null is the result of the call.
 

 
Twitter integration

There are a number of third party Twitter libraries for ActionScript out there, but since Twitter just uses the standard OAuth protocol, I find it easiest to use the oauth-as3 library that Shannon created above. It works perfectly and can be applied to any site that uses OAuth.
 
Logging in to Twitter
Authentication for Twitter can take a few different forms depending on if you’re using a mobile/desktop app or a web application. The solution I’ve used isn’t necessarily a perfect one but it felt like the way that most respected the OAuth protocol while also being an okay user experience. In this example I’m using Twitter’s PIN-based authentication and creating a StageWebView window to log in and handle the authorization. Then the user types the PIN into a TextInput box above the StageWebView and makes an API call to Twitter to get an accessToken that can be used to perform actions.
When you set up a Twitter application on the Twitter development site, you get a series of API URLs and keys that need to be used in the authentication process. I set those up as static variables in my code:
 
private var consumerKey:String = "<YOUR CONSUMER KEY>"; private var consumerSecret:String = "<YOUR CONSUMER SECRET>"; private var twitterRequestURL:String = "https://api.twitter.com/oauth/request_token"; private var twitterAuthURL:String = "https://api.twitter.com/oauth/authorize"; private var twitterTokenURL:String = "https://api.twitter.com/oauth/access_token"; private var requestToken:OAuthToken;
Then using those variables, you can use the oauth-as3 API to generate an OAuthConsumer that will give you a consumer token that can be used to let the user log in. Setting up the consumer is just a matter of creating an instance of OAuthConsumer with the consumerKey and consumerSecret specified from Twitter. Then you can build the request using a request loader and call it.
 
consumer = new OAuthConsumer(consumerKey,consumerSecret); var oauth:OAuthRequest = new OAuthRequest(OAuthRequest.HTTP_MEHTOD_GET,twitterRequestURL,null,consumer); var request:URLRequest = new URLRequest(oauth.buildRequest(new OAuthSignatureMethod_HMAC_SHA1())); var loader:URLLoader = new URLLoader(request); loader.addEventListener(Event.COMPLETE,onLoaderComplete);
If the call is successful, the return object includes the information needed to build a requestToken. Using that requestToken the application can build an authorization request which will take the user to Twitter.com and ask them to log in. When they do that, they’ll be prompted to authorize the application and then the PIN number will be displayed.
 
protected function onLoaderComplete(event:Event):void { requestToken = OAuthUtil.getTokenFromResponse(event.currentTarget.data); var authRequest:URLRequest = new URLRequest('http://api.twitter.com/oauth/authorize?oauth_token='+requestToken.key); twitterWebView = new StageWebView(); twitterWebView.viewPort = new Rectangle(0,baseHeight,stage.width,stage.height-baseHeight); twitterWebView.stage = this.stage; twitterWebView.assignFocus(); twitterWebView.loadURL(authRequest.url); }
It’s in this function where I set up the StageWebView that will display the Twitter website. Using the requestToken I build the URL for authorization and load that URL in the StageWebView instance.
At this point the authentication process is out of our hands. The user will walk through the steps on the Twitter website to authorize the application to access their data and when the process is completed, Twitter.com will display a PIN number. The user has to type that PIN into the application and then the application makes a call out to Twitter with that PIN to show that the user has authorized it.
 
var params:Object = new Object(); params.oauth_verifier = tiPinNumber.text; accessRequest = new OAuthRequest(OAuthRequest.HTTP_MEHTOD_GET,twitterTokenURL,params,consumer,requestToken); var accessUrlRequest:URLRequest = new URLRequest(accessRequest.buildRequest(new OAuthSignatureMethod_HMAC_SHA1())); var accessLoader:URLLoader = new URLLoader(accessUrlRequest); accessLoader.addEventListener(Event.COMPLETE,onAccessRequestComplete);
I’ve created a params object with the text value from a TextInput box where the user types the PIN. Then I call the twitterTokenURL using that params object, the consumer information, and the request token. If the call is successful then Twitter will give us an access token that we can store and use to access Twitter in subsequent API calls.
 
protected function onAccessRequestComplete(event:Event):void { accessToken = OAuthUtil.getTokenFromResponse(event.currentTarget.data); thisProfile.twitterAccessKey = accessToken.key; thisProfile.twitterAccessSecret = accessToken.secret; }
In 100 Days of Exercise I store the access key and the access secret in the database so I can use them anytime in the application. The next step is to use those to post to the user’s Twitter stream.
 
Posting to Twitter
The process of posting to Twitter requires building a consumer (for your application-specific information) and an access token (using the access key and the access secret from the call above), and then using that information to create an OAuthRequest. Within that OAuthRequest, you also need to pass in the text of the status update.
 
params.status = taStatus.text; var consumer:OAuthConsumer = new OAuthConsumer(consumerKey,consumerSecret); var token:OAuthToken = new OAuthToken(thisProfile.twitterAccessKey,thisProfile.twitterAccessSecret); var postRequest:OAuthRequest = new OAuthRequest(OAuthRequest.HTTP_MEHTOD_POST,twitterPostUrl,{status:taStatus.text},consumer,token); var urlRequest:URLRequest = new URLRequest(postRequest.buildRequest(new OAuthSignatureMethod_HMAC_SHA1())); urlRequest.method = URLRequestMethod.POST; urlRequest.url = urlRequest.url.replace("&status=" + URLEncoding.encode(params.status),""); urlRequest.data = new URLVariables( "status=" + taStatus.text ); var loader:URLLoader = new URLLoader(urlRequest); loader.addEventListener(Event.COMPLETE,onTwitterPostComplete); loader.addEventListener(IOErrorEvent.IO_ERROR,onTwitterIOError); loader.addEventListener(HTTPStatusEvent.HTTP_STATUS,onTwitterHttpStatus);
There is a lot going on in the code above but the start of it is just setting up the OAuth calls. In order to make the call work you have to put the status variable into a URLVariables object so I strip out the URL encoded status and then attach it as a URLVariable to the data object of the URLRequest.
 

 
Where to go from here

Now you should have an idea of how to integrate Facebook and Twitter features into your mobile app. The authentication workflows can be a little bit complicated but with Facebook the SDK abstracts a lot of it and the oauth-as3 library takes care of the heavy lifting for Twitter.
Here are a few helpful links: