Temple Library for ActionScript 3.0 by MediaMonks Project Home |  API Documentation |  Source |  Downloads
Facebook Module
 

Summary

About

Module for communication with Facebook, using the Graph API or FQL. This is version 3.7.0 of the Temple Facebook Module, build on 2013-11-27. Get the latest version from: http://code.google.com/p/templelibrary/.

Features

This FacebookAPI is based on the Adobe ActionScript 3 SDK for Facebook Platform API, but with some big improvements, like:

Automatic Facebook login

This feature is handled by the FacebookService. The FacebookService will check for each call if extended permissions are required. If there are permissions needed and the user didn't allow those permissions already, the FacebookService will automatically show a login dialog asking for the required permissions.

After the login, the FacebookService will do the requested call. If the user already allowed the needed permissions, the login is skipped. By enabling the autoPermissions (which is enabled by default) the user only needs to accept the permissions right before the call is done. And you (as developer) never have to digg into the documentation to figure out which permissions are required for the calls you need to do. This matches the guide lines for handling revoked permissions. You are still able to request for permissions manually using the login method.

Note: Since the login dialog is a popup, it can be blocked by the browsers popup-blocker. Therefore this should always be preceded by by a click.

Strong typed result objects

The result data received from Facebook will automatically been parsed to typed objects. This will make your code more neat and stable, and allows you to use auto-completion in your code editor. The result data is returned in the data property of the IFacebookResult. Although this property is untyped you can cast the result to the specific type. You should always use the interface for typing, like: IFacebookUserData, IFacebookAlbumData, IFacebookLikeData, IFacebookPhotoData or IFacebookEventData.

Check out this example. Assumed we have a reference to the FacebookAPI stored in the _facebook variable. We can get the data of the user like this:

// Get the data of the user
_facebook.getUser(onUser);

// callback method, called when the data is received and parsed
private function onUser(result:IFacebookResult):void
{
	// check if call was successful
	if (result.success)
	{
		// user will be available in the data property of the result
		var user:IFacebookUserData = IFacebookUserData(result.data);
		user.name;
		user.gender;
	}
}

Specifying the fields to receive from Facebook

Facebook doesn't return every property of a user by default. And some properties require explicit permissions. This can be handled using an IFacebookFields object. You only need to created an IFacebookFields related with the call and set every property you want to receive to true. Like this:

Specifying the received fields of a user, using the FacebookAPI.getUser() method and a FacebookUserFields object.

// Create a new FacebookUserFields object
var fields:FacebookUserFields = new FacebookUserFields();

// set every property you want to receive to true
fields.name = true;
fields.email = true;
fields.birthday = true;

// pass this object with the call
_facebook.getUser(onUser, FacebookConstant.ME, fields);

private function onUser(result:IFacebookResult):void
{
	if (result.success)
	{
		var user:IFacebookUserData = IFacebookUserData(result.data);
		user.name;
		user.email;
		user.birthday;
	}
}

An other example of specifying the fields:

Specifying the received fields of photos, using the FacebookAPI.photos.getPhotos() method and a FacebookPhotoFields object.

// Create a new FacebookPhotoFields object
var FacebookPhotoFields = new FacebookPhotoFields();

// set every property you want to receive to true
fields.id = true; // The id of the photo
fields.thumbnail = true; // url to the thumbnail version of the photo
fields.comments = true; // a list of all the comments on this photo

// pass this object with the call
_facebook.photos.getPhotos(onPhotos, FacebookConstant.ME, fields);

private function onPhotos(result:IFacebookResult):void
{
	if (result.success)
	{
		// a list of all the photos are inside the data property of the result
		var photos:Vector. = Vector.(result.data);
	}
}

Detailed method calls

For almost every call the FacebookAPI has a built-in method with the required and optional arguments. These methods also do some type checking and validation, which makes you application more strict and stable.

Uploading an image to Facebook is as easy as:

// create an image to upload
var image:BitmapData = new BitmapData(640, 480);
image.draw(this);

// upload it
_facebook.photos.upload(image, "Check this image");

Posting a feed on the wall of a friend:

// let's post a URL on the wall of a friend, using a dialog window
_facebook.dialogs.feedDialog(onFeed, friend.id, "http://templelibrary.googlecode.com/")l

Interface based, no Singletons

You can type almost every object as Interface and there is no singleton implementation. Working with interfaces results in cleaner code and can reduce filesize when you work with multiple SWF files. Although the FacebookAPI is not a singleton, it's not recommanded to created multiple FacebookAPI instances, since the FacebookAPI is based on the Adobe ActionScript 3 SDK for Facebook Platform API, which is a singleton.

Call caching

The FacebookService has a built-in caching system. If cache is enabled the FacebookService will retreive the data from it's cache instead of doing a new Facebook call when the call is done before. This can make you application a lot faster. Ofcourse you are still able to force a Facebook call by setting forceReload to true which is one of the arguments in every GET-method. Caching is enabled by default, but can be disabled.

Advanced object caching

All Facebook object will be cached, in a local database, based on their id (which is unique) and are reused. The FacebookAPI will never create the same Facebook Object again, but will reuse the object it already has. If Facebook provides more information, this information will be applied on this object. Reusing these objects result in a faster application, and provides you with more information as the normal Facebook call would do.

Usage of Callbacks and Events

As the 'regular' Facebook API only support callbacks, this FacebookAPI support callbacks and Events. Every method returns an IFacebookCall object which dispatches a Event.COMPLETE event when the call is completed. The FacebookService and FacebookAPI will dispatch a PendingCallEvent.CALL event when a call starts. The FacebookService and FacebookAPI will dispatch a PendingCallEvent.RESULT event when a call is completed.

The FacebookAPI also support callbacks. Every method has a callback argument of type Function. The supplied function must accept one (and only one) argument of type IFacebookResult. If a call succeeded, the success property of the result will be true, if the call supplies data. The requested data is in the dataproperty of the result. If the call failed, the success property of the result will be false. The code or message can contain more information about the failure.

Getting friends, using a callback:

_facebook.friends.getFriends(onFriends);
	
function onFriends(result:IFacebookResult):void
{
	// Callback won't automatically been released when the object is destructed
	// So first we need to check if the currect object is still alive 
	if (isDestructed) return;
	
	if (result.success)
	{
		var friends:Vector.<IFacebookUserData> = Vector.<IFacebookUserData>(result.data);
	}
	else
	{
		Log.error("Getting friends failed: " + result.message);
	}
}

Upload an image, using a callback:

_facebook.photos.upload(image, "Image example with callback", onUpload);

function onUpload(result:IFacebookResult):void
{
	if (result.success)
	{
		// upload completed
	}
	else
	{
		// something went wrong, log the error
		logError(result.message);
	}
}

Getting friends, using events:

_facebook.friends.getFriends().addEventListener(Event.COMPLETE, handleFriendsComplete);
	
function handleFriendsComplete(event:Event):void
{
	var result:IFacebookResult = IFacebookResult(IFacebookCall(event.target).result);
	
	if (result.success)
	{
		var friends:Vector.<IFacebookUserData> = Vector.<IFacebookUserData>(result.data);
	}
	else
	{
		Log.error("Getting friends failed: " + result.message);
	}
} 

Upload an image, using events:

_facebook.photos.upload(image, "Image example with Event").addEventListenerOnce(Event.COMPLETE, handleUploadComplete);

function handleUploadComplete(event:Event):void
{
	// check if the upload was successful
	if (IFacebookCall(event.target).result.success)
	{
		// upload succeeded
	}
	else
	{
		// fail
	}
}

One API for several environments: web, mobile, desktop, standalone or Flash IDE

No matter in which environment you project is running, you can use the same API for Facebook communication!

The FacebookAPI uses an adapter as middle layer between the FacebookService and the Facebook API by Adobe. By using a different adapter you can switch between different environments. For using in the web you should use the FacebookAdapter, for mobile the FacebookMobileAdapter (available in the facebook-mobile module) and for desktop the FacebookDesktopAdapter (available in the facebook-desktop module).

FacebookAccessTokenProvider: Facebook communication from a standalone SWF or in the Flash IDE

Normally it is not possible to communicate with Facebook with an SWF which runs in the Flash IDE or in a standalone Flash Player, since Facebook uses JavaScript for communication, which isn't available in a the Flash IDE or standalone player. Therefor we created the FacebookAccessTokenProvider. The FacebookAccessTokenProvider runs in the browser and communicates with Facebook using JavaScript and communicates with the standalone SWF using LocalConnection.

To use the FacebookAccessTokenProvider, use the FacebookStandaloneAdapter and open the FacebookAccessTokenProvider in your browser.

Note: FacebookAccessTokenProvider does not use your Facebook Application, but uses his own. Therefore you should only use it for development purposes.

Note: Dialogs won't open in your application if you are using the FacebookAccessTokenProvider. These dialogs are opened in the browser in the FacebookAccessTokenProvider.

Same result objects for both Graph and FQL calls

Since all objects from Facebook are converted to strong typed objects by the FacebookService, results from both the Graph API as FQL are the same. Facebook uses different naming for properties in FQL, but these are automatically converted by the FacebookAPI.

The convertion of the properties is done by using the Alias metadata tag. Therefore you should always compile your project using the -keep-as3-metadata+=Alias argument:

-keep-as3-metadata+=Alias

Content

The Facebook module contains the following folders:

/bin
Contains the SWC of the Facebook module.
/doc
Contains the documentation of the Facebook module.
/examples
Contains some examples of the Facebook module.
/extended
Contains some additional classes which can be very handy for your project, but these classes are required for using the module. This class may also be dependent on other modules which are supplied with this module.
/lib
Contains the SWC files of other Temple modules which are needed for this module.
/source
Contains the source (.as) files of this module.
/tools
Contains ANT scripts which are used to generate docs, examples, swc etc... (This folder is not available in the zip file.)

Dependencies

The Temple Facebook module needs to following Temple modules:

The /extended folder contains some additional classes which might be dependend on other modules.

Getting started

First read

The Temple Facebook module is based on Adobe ActionScript 3 SDK for Facebook Platform API, therefore it is recommanded to read "Adobe Flash and Facebook", "Create your first Flex and Facebook application" and "Build your first Facebook application" on the Adobe site.

Register your App

Create your Facebook App on the Facebook Developers website. 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. NOTE: You must be a verified user if you want to create an Facebook App.

Edit your HTML

Add the Facebook Javascript in your HTML by adding the following line in the head section of the HTML file.

<script type="text/javascript" src="//connect.facebook.net/en_US/all.js"></script">

Also add a div tag with "fb-root" as id in the body of the HTML.

<div id="fb-root""></div">

Add channel.html

The channel file addresses some issues with cross domain communication in certain browsers. Pass the url of the channel.html to the constructor of the FacebookAdapter. This must be an absolute path and protocol (http(s)) and (sub)domain must strictly match the url of the application. See also the JavaScript SDK documentation on Facebook. The contents of the channel.html file can be just a single line:

<script src="http://connect.facebook.net/en_US/all.js"></script>

Create ActionScript Code

Create the FacebookAPI with a FacebookAdapter and call the init() on the FacebookAPI with the applicationId of your Facebook APP. NOTE: If the SWF is running in a secure environment (https) you must set the secure argument in the constructor of the FacebookAdapter to true, otherwise it must be false. To define it the SWF is running in a secure environment you can check the url of the loaderInfo.

Create a FacebookAPI

// We check if the SWF is running in a secure environment (by checking the url on "https") and set secure to true
var secure:Boolean = loaderInfo.url.indexOf('https:') != -1;

// Pass the url to the channel url, mind the protocol (http(s)) and (sub)domain!
var channel:String;
if (secure)
{
	channel = "https://www.domain.com/channel.html";
}
else
{
	channel = "http://www.domain.com/channel.html";
}

// Create a FacebookAPI with a FacebookAdapter
var facebook:IFacebookAPI = new FacebookAPI(new FacebookAdapter(secure, channel));

// initialize app with application id
facebook.init("application id");

Troubleshooting

If you have problems connecting to Facebook, check the following:

Examples

Check out the /examples folder for all examples. This folder also contains a list of all available examples.

Note: every example has an XML file which is an ANT build file which can be used to build the example.