C/C++ Guides

Home

The Facebook C++ Library

The MoSync Facebook C++ Library implements most of the Facebook Graph C API. Here we describe how to connect to Facebook through the Facebook library, retrieve information about them, post links, vidoes and other object types, create new albums, and a whole host of other cool operations.

Introduction

Facebook is a modeled as a social graph. Its official API, the Facebook Graph API, represents the objects in the graph (people, photos, albums, events...) and the connections between them (friend relationships, photo tags...).
 
Every object in the social graph has a unique ID. You can fetch any object from Facebook if you know the ID. Alternatively, people with usernames can be accessed using their username as an ID. There is also a special identifier "me" which refers to the current user.
 
You can retrieve the public information about a user (first name, last name, profile picture) by using the ID or the username. To get additional information about a user, you must first get their permission for which you need to get an access token. After you obtain the access token, you can perform authorized requests and publish on behalf of that user.
 
The MoSync Facebook Library defines a FacebookManager class that provides the interface between the Facebook platform and your own application. Use this class if you want to retrieve data, publish on Facebook, or retrieve an access token for your application.

Authentication and access tokens

Authentication involves retrieving the access token and asking for extended permissions. For the official Facebook documentation on the authorization flow see: http://developers.facebook.com/docs/authentication/.
 
Retrieving a user access token allows your application to access a user’s basic information (that is information that is available publicly or by default on Facebook). If your application needs more than this basic information, you must request specific permissions from the user.
 
To get the access token from Facebook you must first redirect the user to the Facebook OAuth Dialog. With the MoSync Facebook Library this is very easy:

String appID = "13234625675"; //the application id
mFacebookManager = new FacebookManager( app_ID );
String oAuthUrl = mFacebookManager->getOAuthUrl();
mLoginScreen = new FacebookLoginScreen();
mLoginScreen->setUrl ( oAuthUrl );
mLoginScreen->show(); //displays the login screen

After the user logs in, we are redirected to the redirect_uri. The access token is passed in the redirect_uri. The redirect_uri must be parsed to get the access token. An example of how to extract the access token can be found in our FacebookDemo example application in FacebookDemoMoblet::customEvent.
 
After retrieving the access token, we must send it to the FacebookManager:

mFacebookManager->setAccessToken(accessToken); 

Permissions

You must request specific permissions from the user if your app needs more information than the user has made available to everyone on Facebook. To do this, pass the FacebookManager the permissions you need.

Note: If your application also needs permissions, you must pass those permissions to FacebookManager when it is first created.
 
In the MoSync Facebook Library we specialize the GetPermissionsFor template class for each Facebook object type. It is used to fill a Set object with the permissions that are needed to make connections to a Facebook object or to publish an object.

MAUtil::Set<MAUtil::String> permissions;

To get the permissions needed to retrieve a Note object for the current user or current user’s friend (also for the connections of Note objects) we use:

// "user_notes" "friends_notes"
GetPermissionsFor<Note>::retrievingData(permissions); 

To get the permissions needed to publish a note on behalf of the user or user’s friend we use:

//"create_note", "publish_stream"
GetPermissionsFor<Note>::publishingData(permissions); 

To get all the permissions available, so that we can make any request (retrieve data, connections, and publish), we use:

// "user_notes" , "friends_notes", "create_note", "publish_stream"
GetPermissionsFor<Note>::allPosibleRequests(permissions); 

You can also just get the permissions needed to retrieve a field from a user object (for example, a biography), or for a connection, as we show in the example below:

MAUtil::Set<MAUtil::String> permissions;
 
permissions.insert("offline_access"); //ask for a access_token that doesn’t expire
GetPermissionsFor<User>::Retrieve::onlyConnections(permissions);
GetPermissionsFor<User>::publishingData(permissions);
GetPermissionsFor<Album>::allPosibleRequests(permissions);
GetPermissionsFor<Checkin>::allPosibleRequests(permissions);
GetPermissionsFor<Comment>::allPosibleRequests(permissions);
GetPermissionsFor<Note>::allPosibleRequests(permissions);
GetPermissionsFor<Photo>::allPosibleRequests(permissions);
GetPermissionsFor<Post>::allPosibleRequests(permissions);
 
//the app id that is generated when you create your application
String application_ID = "7125765764";
 
mFacebookManager = new FacebookManager(application_ID, permissions);
String oAuthUrl = mFacebookManager->getOAuthUrl();
 
mLoginScreen = new FacebookLoginScreen();
mLoginScreen->setUrl(oAuthUrl);
mLoginScreen->show(); //this displays the login screen

Implemented Graph API objects

Our Facebook Library implements most of the Facebook objects described in the Graph API documentation (http://developers.facebook.com/docs/reference/api/). The implementation can be found in /Facebook_lib/GraphAPI/GetFacebookObjects/FacebookObjects in your installed MoSync package.

Objects currently implemented include:

  • Album
  • Checkin
  • Comment
  • Event
  • FriendList
  • Group
  • Link
  • Note
  • Photo
  • Post
  • StatusMessage
  • User 
  • Video

Fetching public information about an object

You can access the properties of an object using the FacebookManager. To retrieve an object your application has to register as an ObjectRequestListener with the FacebookManager. To do this, we inherit from ObjectRequestListener and override the functions we are interested in.

If we want to retrieve User objects, we override void facebookObjectReceived(const User &). If we want to retrieve Album objects, we override void facebookObjectReceived(const Album &).

For example, to access the public information about a User, with the username btaylor and an album with the id 99394368305 (Coca-Cola's wall photos):

class MyApplication: public ObjectRequestListener
{
public:
   // ObjectRequestListener override. This function will be called by the
   // FacebookManager when a User object is retrieved from Facebook
   virtual void facebookObjectReceived(const User &object);

   // ObjectRequestListener override. This function will be called by the
   // FacebookManager when an Album object is retrieved from Facebook.
   virtual void facebookObjectReceived(const Album &object);

   //ObjectRequestListener override. Called when the request fails.
   virtual void queryError(int code, const MAUtil::String &path);
};

String application_ID = "13234625675"; //the application id
mFacebookManager = new FacebookManager( application_ID );

mFacebookManager->setObjectRequestListener(this);
mFacebookManager->requestObject<User>(btaylor);
mFacebookManager->requestObject<Album>(99394368305); 

When the response from Facebook is received, the JSON data is parsed and converted to the type of object we requested (e.g User). FacebookManager sends this object to the listener.

Retrieving connections

We use FacebookManager to retrieve connections for an object. To make a connection request we need to know the ID of the object. If the Facebook object is the current user, we can use me instead of an ID. We also need to inherit from ConnectionsManagerListener and register with the FacebookManager as a listener.
 
To see what connections are available for an object we use the Connections template class found in /GetConnections/Connections.h. The template is specialized for every Facebook object type defined by the library.
 
To see what connections are available for an album, we use the Connections<Album> class. Connections<Album> has four static functions that correspond to the four connections an Album can have: likes, photos, comments, picture. Each returns a string representing the keyword for that connection. For example, Connections<Album>::likes() returns "likes".
 
The Connections<Checkin> class defines two functions that return the keywords for the two connections that a Checkin has (likes and comments), so to ask for all the connections a Checkin we use:

mFacebookManager->requestConnection( ckeckin_id, Connections<Checkin>::likes() );
mFacebookManager->requestConnection( checkin_id, Connections<Checkin>::comments() );

To request the albums, feed, and notes connections for the current user, and also request the comments connections for one of the user’s albums we use:

class MyApplication : public ConnectionsManagerListener
{
public:
    MyApplication();
 
    //The following functions are ConnectionsManagerListener  overrides.
    //connType parameter - represents the keyword for the connection we requested.
    //For the news feed for example it will be "feed".
    //objectId parameter -  string representing the id of the object for which
    // we requested the connection.
 
    //Function called by FacebookManager when the "albums" connection
    //is retrieved from Facebook.
    void received( const Vector<Album> &albums, const String &connType, const String &objectId );
 
    //Function called by FacebookManager when the "feed"  connection
    //is retrieved from Facebook.
    void received( const Vector<Post> &posts, const String &connType, const String objectId );
 
    //Function called by FacebookManager when the "notes"  connection
    //is retrieved from Facebook.
    void received(   const Vector<Note> &notes, const String &connType, const MAUtil::String objectId ) ;
 
    //Function called by FacebookManager when the "comments" connection
    //is retrieved from //Facebook
    void received( const MAUtil::Vector<Comment> &comments, const MAUtil::String  &connType, const String &objectId )
 
    //override of ConnectionsManagerListener called when the request failed
    void queryError(int code, const MAUtil::String &path) ;
};
 
MyApplication::MyApplication()
{
    //the application id
    String application_ID = "13234625675";
    mFacebookManager = new FacebookManager( application_ID );
    mFacebookManager->setConnectionRequestListener(this);
   
    //request for the albums connection for the curent user
    mFacebookManager->requestConnection( Connections<User>::albums(), "me" );
   
    //request for the notes connection for the curent user
    mFacebookManager->requestConnection( Connections<User>::notes(), "me");
 
    //request for the feed connection for the curent user
    mFacebookManager->requestConnection( Connections<User>::feed() , "me");   
}

void MyApplication::received(  const Vector<Album> &albums, const String &connType, const String &objectId)  
{   
    Album firstAlbum = albums[0];
    mFacebookManager->requestConnection( Connections<User>::comments(), firstAlbum.getId() );
}

We can request only the fields you want from an object. For example, if we just want to retrieve the name and ID of all of the user’s albums we do not want any other fields. To do this we call the overload function requestConnection and pass it a vector with jus the fields we want:

Vector<String> fields;
fields.add("id");
fields.add("name");

mFacebookManager->requestConnection("albums", fields, "me");

Publishing To and Deleting From Facebook   

We use FacebookManager to publish to Facebook or to delete Facebook objects. To get the result of a publish or delete request, we inherit from the PublishingListener class and register with the FacebookManager as a PublishingListener:

class MyApplication: public PublishingListener
{
public:

    //PublishingListener override
    //This function is called when a remove or an unlike request
     //was completed successfuly
    void publishingResponseReceived(bool success, const String &path);

    //PublishingListener override
    //This function is called when a new Facebook object was created successfully.
    void publishingResponseReceived(bool const String &newObjectId, const String &path);

    //PublishingListener override.  Called when the request fails.
    virtual void queryError(int code, const MAUtil::String &path);
};

String application_ID = "13234625675";  //the application id
mFacebookManager = new FacebookManager( application_ID );

MyApplication *myApp = new MyApplication();

//register as a PublishingListener, so that MyApplication is informed
//about the result of the publish request.
mFacebookManager->setPublishingListener(myApp); 

Liking and unliking objects

To like a Facebook object we call the FacebookManager function void Like(const String &id). The "id" parameter is the ID of the object to be liked. To like an album, for example, we use:

mFacebookManager->like( album.getId() );

Similarly, to unlike a Facebook object we call the FacebookManager function void Unlike(const String &id).

mFacebookManager->unlike( comment.getId() ); 

Here comment represents some Comment object we retrieved from Facebook.

Adding an object

Various types of objects can be added to Facebook through the functions in the FacebookManager class. For a comprehensive list of the functions available through this class, see the MoSync API Reference.

Objects that can be added include:

  • Comments
  • Users to FriendLists or Groups
  • FriendLists
  • Events and EventResponses
  • Notes
  • Albums
  • Checkins
  • Posts, Links, and StatusMessages on Walls

To add a comment on a Facebook object we call the FacebookManager function addComment:

String myMessage = "I like this post";
mFacebookManager-> addComment(post.getId(), myMessage);

Here we use post.getId to identify the object to which we wish to add the comment. Similarly we can use the FacebookManager function addUser to add a User object to a FriendList:

mFacebookManager->addUser( myFriendList.getId(), "7692649746983");

Here "7692649746983" is the unique ID of the friend we want to add.

Some functions in FacebookManager are a little more complicated. To add an event on behalf of the current user (or one of that user's friends) we use the function addEvent which requires several parameters, along with some optional ones:

void addEvent(
     const MAUtil::String &USER_ID,                                //mandatory
    const MAUtil::String &eventName,                           //madatory
    const UnixTimeStamp &eventStart_time,                      //mandatory
    const UnixTimeStamp &eventEnd_time = UnixTimeStamp(),      //optional
    const MAUtil::String &message= "",                         //optional
    const MAUtil::String &location = "",                       //optional
    const MAUtil::String &privacyType = "OPEN");               //optional

For example:

//event name
String eventName = "party";   

//event starts in 06/12/2012 at 8:15 :30
UnixTimeStamp startTime(Date("2012", "12", "6"), Time("8","15","30"));

//event ends in 06/12/2012 at 11:20:00
UnixTimeStamp endTime(Date("2012", "12", "6"), Time("11", "20","00"));

//the event’s description
String eventDescription = " MoSync annual Christmas party";

//the event takes place in Stockholm
String eventLocation = "Stockholm";

mFacebookManager->addEvent(  "me",
eventName,
startTime,
endTime,   
eventDescription,
eventLocation);

To add a Post on the user’s wall (or on one of the user's friends walls) we call addPostOnWall:

void addPostOnWall(  
    const MAUtil::String &ID,                       //mandatory
    const MAUtil::String &message,                  //mandatory
    const MAUtil::String &link,                     //mandatory
    const MAUtil::String &name = "",                //optional
    const MAUtil::String &caption = "",             //optional
    const MAUtil::String &description = "");        //optional           

For example:

mFacebookManager->addPostOnWall ( "me",                   //id
    "Post added with MOSYN SDK",                          //message
    "http://www.youtube.com/watch?v=FL7yD-0pqZg",         //link
    "New Post :)",                                        //name
    "Link from You Tube"                                  //caption       
    "Testing adding a post on wall with MOSYNC_SDK");     //description

The result will be a wall post that looks something like this:

Removing objects

FacebookManager provides a set of functions for removing objects the Graph API. The objects that can be removed include:

  • Users from FriendLists and Groups
  • Comments
  • FriendLists
  • Notes

To remove a user from a FriendList we call the FacebookManager function removeUserFrom:

String myFriendListID = "1234567";
String friendID = "0101010101";
mFacebookManager->removeUserFrom ( myFriendListID, friendID);

A larger example

In this example we retrieve albums, posting a link on the user's wall, post a link for all the user's friends, add a like and a comment to an album, and delete a FriendList.

 

class MyApplication: public MAUtil::Moblet, public ConnectionsManagerListener, public PublishingListener
{
public:

   MyApplication();

   // ConnectionsManagerListener overrides

   /*
   * This function is called when a "albums" Connection was completed sucessfully
   */
   virtual void received(const MAUtil::Vector<Album> &albums,
   const MAUtil::String &connType,
   const MAUtil::String &objetcId);

   /*
   * This function is called when the "likes", "movies", "music", "books", "accounts",
   * "activity", "friendlists", "interests" and "television" Connection was requested.
   * @param connType - the ConnectionType. It can have the following values: "likes",
   * "movies", "music", "books", "accounts", "activity", "friendlists", "interests"
   * and "television"
   */
   virtual void received(const MAUtil::Vector<CategoryData> &likes,
   const MAUtil::String &connType,
   const MAUtil::String &objetcId);

   /*
   * This function is called when the "friends", "members" or "tags" Connection
   * was requested.
   * @param connType - the ConnectionType. It can have the following values:
   * "friends", "members" or "tags"
   */
   virtual void received(const MAUtil::Vector<IdNamePair> &friends,
   const MAUtil::String &connType,
   const MAUtil::String &objetcId);

   /*
   * This function is called when a Connection was requested, and the request failed
   */
   virtual void errorReceivingConnection(int code,
   const MAUtil::String &connType,
   const MAUtil::String &id);

   // PublishingListener overrides

   / *
   * This function is called when a remove or an unlike request was
   * completed sucessfully.
   */
   virtual void publishingResponseReceived(bool success, const MAUtil::String &path);

   /*
   * This function is called when a new object was created successfully
   * (Album, Like, Comment, StatusMessage etc).
   */
   virtual void publishingResponseReceived(const MAUtil::String &data, 
   const MAUtil::String &path);

   /*
   * This function is called when a publish/remove request failed
   */
   virtual void queryError(int code, const MAUtil::String &path);

private:

   void requestAlbumsConnection();
   void addComment(const String &id);
   void addLike(const String &id);
   void postLinkOnWall(const String &id);
   void requestFriendListsConnection();
   void deleteFriendList(const String &id);

private:

   FacebookManager *mFacebookManager;

};

MyApplication::MyApplication()
{
   String applicationId = "265721237478169";

   mFacebookManager = new FacebookManager(applicationId);
   mFacebookManager->setAccessToken("476927849827395873465923695798723"); 

   //register as a ConnectionManagerListener so that we retrieve the
   //requested data from FacebookManager
   mFacebookManager->setConnectionRequestListener(this);

   //register as a PublishingListener so that we are informed by the
   //FacebookManager about the result of the publish request
   mFacebookManager->setPublishingListener(this);

   //request the albums of the user. We will add a comment and a like
   //to the first album
   requestAlbumsConnection();

   //request the FriendLists of the user. We will delete the first FriendList
   requestFriendListsConnection();

   //Posting a link on wall for the user
   
   // We post for the current user (that logged in), so we can use "me" as an id.
   postLinkOnWall("me");  
}

void MyApplication::requestAlbumsConnection()
{
   mFacebookManager->requestConnection("albums");
}

void MyApplication::addComment(const String &ID)
{
   mFacebookManager->addComment("Testing adding a comment with MOSYNC SDK", ID); //adding the comment to the object with the id "ID"
}

void MyApplication::Like(const String &ID)
{
   mFacebookManager->Like(ID); //like the Facebook objetc with the id "ID"
}

void MyApplication::postLinkOnWall(const String &id)
{
   mFacebookManager->addLinkOnWall( id, //the id.
   "http://www.mosync.com/", //the link we want to post
   "Testing posting a link on wall with MOSYNC SDK"); //the message to display.
}

void MyApplication::requestFriendListsConnection()
{
   mFacebookManager->requestConnection("friendlists");
}

void MyApplication::deleteFriendList(const String &id)
{
   mFacebookManager->removeFriendList(id);
}

//Retrieving albums

void MyApplication::received(const MAUtil::Vector<Album> &albums,
const MAUtil::String &connType,
const MAUtil::String &objetcId)
{
   Album album = albums[0];

   addComment( album.getId() ); //Adding a comment to an album
   addLike( album.getId() );    //Adding a like to an album
}

void MyApplication::received(const MAUtil::Vector<CategoryData> &friendlists,
const MAUtil::String &connType,
const MAUtil::String &objetcId)
{
   if( connType == "friendlists" )
   {
       deleteFriendList( friendlists[0].getId() ); // f) deleting a FriendList.
   }
}

void MyApplication::received(const MAUtil::Vector<IdNamePair> &friends,
const MAUtil::String &connType,
const MAUtil::String &objetcId)
{
   if( connType == "friends" )
   {
       for (int i=0; i<friends.Size(); i++) //Posting a link for all the user's friends
       postLinkOnWall( friends[i].getId() );
   }
}

MoSync SDK 3.3
Copyright © 2013 MoSync AB
www.mosync.com