‹ Facebook Doc Home

Facebook Integration Guide

For the C++ version of cocos2d-x v3.x - (all other versions)

Prerequisites

Integration

Open a terminal and use the following command to install the SDKBOX Facebook plugin. Make sure you setup the SDKBOX installer correctly.

$ sdkbox import facebook

Important Notice

Please make sure the following settings in your project for plugin to function correctly.

Disable App Transport Security

Adding the following entry to the info.plist file:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

It should look something like this:

Disable Bitcode support

You have to turn off Bitcode support. If you don't cocos2d-x will fail to build.

Set your game requires full screen

If your game doesn't support all screen orientations you will need to check Requires full screen in Xcode. If you do not, your app will fail Apple's submission process.

Whitelist canOpenURL function

This depends on what plugins are in your project. You may need to add the required entry to the info.plist, under LSApplicationQueriesSchemes.

Follow this link

Extra steps

The following step assuming you already registered as a Facebook Developer And created a new APP on Facebook, If not please follow up the Setup Facebook App section below.

Setup iOS

#import <FBSDKCoreKit/FBSDKCoreKit.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // ...

  //
  // **************************
  // !! IMPORTANT !!
  // **************************
  //
  // call [[FBSDKApplicationDelegate sharedInstance] application:didFinishLaunchingWithOptions
  // before app->run()

  BOOL ret = [[FBSDKApplicationDelegate sharedInstance] application:application
                                      didFinishLaunchingWithOptions:launchOptions];
  app->run();
  return ret;
}

- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
  return [[FBSDKApplicationDelegate sharedInstance] application:application
                                                         openURL:url
                                               sourceApplication:sourceApplication
                                                      annotation:annotation];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
  [FBSDKAppEvents activateApp];
}

login doesn't work on simulator on iOS 10, Xcode8

Go to the Project Target and then Capabilities and switch Keychain Sharing ON.

http://stackoverflow.com/a/39788102/5443510

Setup Android

JSON Configuration

SDKBOX Installer will automatically create a sample configuration sdkbox_config.json for you

options

The Facebook App ID to be used by the SDK.

The url scheme suffix to be used by the SDK.

Here is an example of the Facebook configuration you can enable/disable debug mode for Facebook here

"Facebook":
{
    "debug":true,
    "app_id":"",
    "url_scheme_suffix":""
}

Setup Facebook App

In order to setup your Facebook app correctly to avail all services provided by SDKBOX, please go through the link mentioned below - Setup Facebook App for SDKBOX

Usage

Initialize Facebook

Initialize the plugin where appropriate in your code. We recommend to do this in the AppDelegate::applicationDidFinishLaunching() or AppController:didFinishLaunchingWithOptions(). Make sure to include the appropriate headers:

#include "PluginFacebook/PluginFacebook.h"
AppDelegate::applicationDidFinishLaunching()
{
     sdkbox::PluginFacebook::init();
}

Using Facebook

Login

First the user needs to login to Facebook in order to use it.

sdkbox::PluginFacebook::login();

If a user doesn't want to use Facebook functionality anymore, logout.

sdkbox::PluginFacebook::logout();

You can check whether user already logged in using

sdkbox::PluginFacebook::isLoggedIn();

Note: user only needs to perform login once, unless they logout

Permissions

Facebook requires you to ask for the user's permission before you can perform actions, such as, posting on the user's behalf. There are two types of permission read and publish You can get a complete list of permissions here

SDKBOX provides the most commonly used permissions:

To request a permission, you do so by specifying what you want:

sdkbox::PluginFacebook::requestReadPermissions({FB_PERM_READ_PUBLIC_PROFILE, FB_PERM_READ_USER_FRIENDS});
sdkbox::PluginFacebook::requestPublishPermissions({FB_PERM_PUBLISH_POST});

Share

There are two types of sharing functionality.

sdkbox::FBShareInfo info;
info.type  = sdkbox::FB_LINK;
info.link  = "http://www.cocos2d-x.org";
info.title = "cocos2d-x";
info.text  = "Best Game Engine";
info.image = "http://cocos2d-x.org/images/logo.png";
sdkbox::PluginFacebook::share(info);

share a photo:

sdkbox::FBShareInfo info;
info.type  = sdkbox::FB_PHOTO;
info.title = "My Photo";
info.image = __path to image__;
sdkbox::PluginFacebook::share(info);

present a share dialog:

sdkbox::FBShareInfo info;
info.type  = sdkbox::FB_LINK;
info.link  = "http://www.cocos2d-x.org";
info.title = "cocos2d-x";
info.text  = "Best Game Engine";
info.image = "http://cocos2d-x.org/images/logo.png";
sdkbox::PluginFacebook::dialog(info);

share a photo with comments:

sdkbox::FBShareInfo info;
info.type  = sdkbox::FB_PHOTO;
info.title = "My Photo";
info.image = __path to image__;
sdkbox::PluginFacebook::dialog(info);

Note: sharing photo with comments requires the Facebook app to be installed on the device.

Invite

There are both standard and custom Invite dialogs available to use when inviting your Friends.

When using the standard invite dialog, it is necessary to select the friends to send the invitation request too. The API call is inviteFriends() passing in an app link url and a preview image. Example:

sdkbox::PluginFacebook::inviteFriends(
  "https://fb.me/322164761287181",
  "http://www.cocos2d-x.org/attachments/801/cocos2dx_portrait.png");

Note: Contrary to what it may seem the app link url, it is not an App Store or Google Play application url. You must follow the instructions on this page and use the resulting url as the app_link_url parameter. Facebook hosts this file for the developer, but anyone could host their own file using this format

At runtime, a custom message can be attached to the invite request. It is not possible to set a predefined invite message.

Creating a custom invite dialog is a two step process, starting with a call to requestInvitableFriends() then a call to inviteFriendsWithInviteIds() to actually send the invites. Example:

std::vector<std::string> vec;
vec.push_back(invitable_token);
sdkbox::PluginFacebook::inviteFriendsWithInviteIds(vec, "Invitation title", "Invitation text up to 60 chars.");

The requestInvitableFriends() function has a Bundle(map) parameter, where the developer can define a few flags:

Flag Description
fields a comma separated values of the fields you want to get from your invitable friend’s profiles.
exclude_ids a comma separated FB ids to exclude from the result.
limit number of friends per page.

A call to requestInvitableFriends() will return a different collection of friends per call, and it is Facebook's decision which ones to return first. This function returns a FBInvitableFriendsInfo object, which will contain a collection of the friends data and a pagination cursor object which has URLS for requesting the next and previous page of invitable friends.

The custom invite dialog is only available for games with a canvas implementation for the Facebook application. The canvas must be defined but doesn't need to how any web content. If the canvas is not defined a standard invite dialog is used instead.

Graph API

You can perform Graph API using the api function

For example, to get the friend list:

sdkbox::PluginFacebook::FBAPIParam params;
sdkbox::PluginFacebook::api("/me/friends", "GET", params, "/me/friends");

Facebook events

This allows you to catch Facebook events so that you can perform operations after Facebook events have occurred.

#include "PluginFacebook/PluginFacebook.h"
class MyClass : public sdkbox::FacebookListener
{
private:
  void onLogin(bool isLogin, const std::string& msg);
  void onPermission(bool isLogin, const std::string& msg);
  void onAPI(const std::string& tag, const std::string& jsonData);
  void onSharedSuccess(const std::string& message);
  void onSharedFailed(const std::string& message);
  void onSharedCancel();
};
sdkbox::PluginFacebook::setListener(this);

API Reference

Methods

static void init ( ) ;

initialize the plugin instance.

static void setListener ( FacebookListener * listener ) ;

Set listener to listen for facebook events

static FacebookListener * getListener ( ) ;

Get the listener

static void removeListener ( ) ;

Remove the listener, and can't listen to events anymore

static void login ( ) ;

log in

static void login ( std::vector <std::string> & permissions ) ;
static void requestReadPermissions ( const std::vector <std::string> & permissions ) ;

log in with specific read permissions, conflict with publish permissions https://developers.facebook.com/docs/facebook-login/permissions

static void requestPublishPermissions ( const std::vector <std::string> & permissions ) ;

log in with specific public permissions https://developers.facebook.com/docs/facebook-login/permissions

static void logout ( ) ;

log out

static bool isLoggedIn ( ) ;

Check whether the user logined or not

static std::string getUserID ( ) ;

get UserID

static std::string getAccessToken ( ) ;

get AccessToken

static std::vector <std::string> getPermissionList ( ) ;

get permissoin list

static void share ( const FBShareInfo & info ) ;

share

static void dialog ( const FBShareInfo & info ) ;

open a dialog of Facebook app or WebDialog (dialog with photo only avaible with native Facebook app)

static std::string getSDKVersion ( ) ;

return the version of Facebook SDK

static void api ( const std::string & path ,
                  const std::string & method ,
                  const FBAPIParam & params ,
                  const std::string & tag ) ;

use Facebook Open Graph api https://developers.facebook.com/docs/ios/graph

static void fetchFriends ( ) ;

fetch friends data from Facebook

Only friends who has installed the app are returned in API v2.0 and higher of Facebook. The "total_count" in summary represents the total number of friends, including those who haven't installed the app. https://developers.facebook.com/docs/apps/changelog#v2_0

static std::vector <FBGraphUser> getFriends ( ) ;

get friends info

static bool canPresentWithFBApp ( const FBShareInfo & info ) ;

check whether can present Facebook App

static void requestInvitableFriends ( const FBAPIParam & ) ;

Get a vector of invitable friends info which can be used to build a custom friends invite dialog.

static void inviteFriendsWithInviteIds ( const std::vector <std::string> & invite_ids ,
                                         const std::string & title ,
                                         const std::string & invite_text ) ;

Invite friends based on the result obtained from a call to requestInvitableFriends

static void inviteFriends ( const std::string & app_link_url ,
                            const std::string & preview_image_url ) ;

Use the default FB dialog to invite friends.

static void setAppId ( const std::string& appId );

Set the Facebook App ID to be used by the FB SDK.

static void setAppURLSchemeSuffix ( const std::string & appURLSchemeSuffix );

Set the app url scheme suffix used by the FB SDK.

Listeners

void onLogin ( bool isLogin , const std::string & msg );
void onSharedSuccess ( const std::string & message );
void onSharedFailed ( const std::string & message );
void onSharedCancel ( );
void onAPI ( const std::string & key , const std::string & jsonData );
void onPermission ( bool isLogin , const std::string & msg );
void onFetchFriends ( bool ok , const std::string & msg );
void onRequestInvitableFriends ( const FBInvitableFriendsInfo & friends );
void onInviteFriendsWithInviteIdsResult ( bool result ,
                                          const std::string & msg );
void onInviteFriendsResult ( bool result , const std::string & msg );
void onGetUserInfo ( const FBGraphUser & userInfo );

Manual Integration

If the SDKBOX Installer fails to complete successfully, it is possible to integrate SDKBOX manually. If the installer complete successfully, please do not complete anymore of this document. It is not necessary.

These steps are listed last in this document on purpose as they are seldom needed. If you find yourself using these steps, please, after completing, double back and re-read the steps above for other integration items.

Manual Integration For iOS

Drag and drop the following frameworks from the plugins/ios folder of theFacebook bundle into your Xcode project, check Copy items if needed when adding frameworks:

sdkbox.framework

PluginFacebook.framework

The above frameworks depend upon a large number of other frameworks. You also need to add the following system frameworks, if you don't already have them:

Security.framework

AdSupport.framework

Manual Integration For Android

SDKBOX supports three different kinds of Android projects command-line, eclipse and Android Studio.

Copy Files

Copy the following jar files from plugin/android/libs folder of this bundle into your project’s /libs folder.

PluginFacebook.jar

sdkbox.jar

Copy the facebook_lib directories from plugin/android/libs to your <project_root>/libs/ directory.

Copy jni libs

Copy and overwrite all the folders from plugin/android/jni to your <project_root>/jni/ directory.

Note: sdkbox link with gnustl by default, if your project link with c++static please replace the files in <project_root>/jni/<plugin_name>/libs with files in <project_root>/jni/<plugin_name>/libs_c++_static folder

Edit AndroidManifest.xml

Include the following permissions above the application tag:

  <uses-permission android:name="android.permission.INTERNET" />

There are also a few necessary meta-data tags that also need to be added:

<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
<activity android:name="com.facebook.FacebookActivity"
  android:configChanges=
         "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
  android:theme="@android:style/Theme.Translucent.NoTitleBar"
  android:label="@string/app_name" />

  <provider android:authorities="com.facebook.app.FacebookContentProvider__replace_with_your_app_id__"
  android:name="com.facebook.FacebookContentProvider"
  android:exported="true" />

Edit strings.xml

Open res/values/strings.xml, Add a new string with the name facebook_app_id and value as your Facebook App ID. Example:

  <?xml version="1.0" encoding="utf-8"?>
  <resources>
      <string name="app_name">facebook</string>
      <string name="facebook_app_id">280194012150923</string>
  </resources>

Edit Android.mk

Edit <project_root>/jni/Android.mk to:

Add additional requirements to LOCAL_WHOLE_STATIC_LIBRARIES:

LOCAL_WHOLE_STATIC_LIBRARIES += PluginFacebook
LOCAL_WHOLE_STATIC_LIBRARIES += sdkbox

Add a call to:

$(call import-add-path,$(LOCAL_PATH))

before any import-module statements.

Add additional import-module statements at the end:

$(call import-module, ./sdkbox)
$(call import-module, ./pluginfacebook)

This means that your ordering should look similar to this:

$(call import-add-path,$(LOCAL_PATH))
$(call import-module, ./sdkbox)
$(call import-module, ./pluginfacebook)

Note: It is important to make sure these statements are above the existing $(call import-module,./prebuilt-mk) statement, if you are using the pre-built libraries.

Modify Application.mk (Cocos2d-x v3.0 to v3.2 only)

Edit <project_root>/jni/Application.mk to make sure APP_STL is defined correctly. If Application.mk contains APP_STL := c++_static, it should be changed to:

APP_STL := gnustl_static

Modify project.properties

Add following line to your project.properties

android.library.reference.1=./libs/facebook_lib

Note: if you already have an android.library.reference.1 you can add another by incrementing the final digit as android.library.reference.2, etc.

Modify Cocos2dxActivity.java

Note: When using Cocos2d-x from source, different versions have Cocos2dxActivity.java in a different location. One way to find the location is to look in proj.android/project.properties. Example: android.library.reference.1=../../cocos2d-x/cocos/platform/android/java

In this case, Cocos2dxActivity.java should be located at:

../../cocos2d-x/cocos/platform/android/java/src/org/cocos2dx/lib/Cocos2dxActivity.java
import android.content.Intent;
import com.sdkbox.plugin.SDKBox;
onLoadNativeLibraries();
SDKBox.init(this);
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
          if(!SDKBox.onActivityResult(requestCode, resultCode, data)) {
            super.onActivityResult(requestCode, resultCode, data);
          }
    }
    @Override
    protected void onStart() {
          super.onStart();
          SDKBox.onStart();
    }
    @Override
    protected void onStop() {
          super.onStop();
          SDKBox.onStop();
    }
    @Override
    protected void onResume() {
          super.onResume();
          SDKBox.onResume();
    }
    @Override
    protected void onPause() {
          super.onPause();
          SDKBox.onPause();
    }
    @Override
    public void onBackPressed() {
          if(!SDKBox.onBackPressed()) {
            super.onBackPressed();
          }
    }

Proguard (optional)

proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt
# facebook
-keep public class com.facebook.** { *; }
-dontwarn com.facebook.**

# cocos2d-x
-keep public class org.cocos2dx.** { *; }
-dontwarn org.cocos2dx.**
-keep public class com.chukong.** { *; }
-dontwarn com.chukong.**

# google play service
-keep public class com.google.android.gms.** { public *; }
-dontwarn com.google.android.gms.**

-keep class * extends java.util.ListResourceBundle {
    protected Object[][] getContents();
}

-keep public class com.google.android.gms.common.internal.safeparcel.SafeParcelable {
    public static final *** NULL;
}

-keepnames @com.google.android.gms.common.annotation.KeepName class *
-keepclassmembernames class * {
    @com.google.android.gms.common.annotation.KeepName *;
}

-keepnames class * implements android.os.Parcelable {
    public static final ** CREATOR;
}

#sdkbox
-keep class com.sdkbox.** { *; }
-dontwarn com.sdkbox.**

Note: Proguard only works with Release builds (i.e cocos run -m release) debug builds do not invoke Proguard rules.