Skip to content

Commit

Permalink
chapter 11 resources
Browse files Browse the repository at this point in the history
  • Loading branch information
slackmoehrle committed Mar 12, 2015
1 parent f278f84 commit 4221197
Show file tree
Hide file tree
Showing 16 changed files with 377 additions and 0 deletions.
Binary file added drafts/11-img/add_facebook_binary_lib.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added drafts/11-img/add_facebook_framework.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added drafts/11-img/add_facebook_project_for_lua.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added drafts/11-img/android_eclipse_add_lib.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added drafts/11-img/android_export_facebook.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added drafts/11-print/add_facebook_binary_lib.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added drafts/11-print/add_facebook_framework.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added drafts/11-print/add_facebook_project_for_lua.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added drafts/11-print/android_eclipse_add_lib.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added drafts/11-print/android_export_facebook.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added drafts/11-web/add_facebook_binary_lib.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added drafts/11-web/add_facebook_framework.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added drafts/11-web/add_facebook_project_for_lua.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added drafts/11-web/android_eclipse_add_lib.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added drafts/11-web/android_export_facebook.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
377 changes: 377 additions & 0 deletions drafts/11.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,377 @@
# Chapter 11: Services

This chapter and it's content are currently undecided. If you wish to contribute,
please provide a [Pull Request](https://github.com/chukong/programmers-guide)

## Facebook
Wouldn't it be great to let your friends see how well you are playing your favorite
game? Maybe even promote the game because you think it is great! __Social Media__
is bringing new aspects to gaming. In times before the only way to share your
success was to call your friends and tell them. __Social networks__ Like Facebook
are insanely popular and to this respect, Cocos2d-x allows you to integrate with
__social networks__ easily. So how do you do it?

### Create a Facebook App
Goto [Facebook](https://developers.facebook.com/apps) to create a Facebook app.

### iOS Integration




#### Integrate your iOS project
**Step1**: Open the Xcode project file. Take `HelloPlugins` in the `plugin/samples/HelloPlugins/proj.ios` for example.

**Step2**: Click on the project root, then choose `TARGETS`->`HelloPlugins`->`Build Phases`->`Link Binary With Libraries`. Click `+` button to popup a sub window. Then click on `Add Other...` button in the sub window. Then find `FacebookSDK.framework` under `plugin/plugins/facebook/proj.ios/sdk/FacebookSDK.framework` to add it.

![](11/add_facebook_framework.jpg)

**Step3**: Refer to [Step 4: Configure your Xcode Project - Getting Started with the Facebook iOS SDK](http://developers.facebook.com/docs/ios/getting-started/#configure) to add `FacebookAppID`, `FacebookDisplayName`, `URL types`, `Bundle identifier` in `Info.plist` file. You can find this file under `ios` folder of your Xcode project. You can see the result below:

![](11/iOS_plist_setting.jpg)

**Step4**: Select target `HelloPlugins` in the project root, open `Build Settings` page, then search for `Other Linker Flags`, and add `-ObjC` linker flag.

![](11/iOS_other_flag_setting.jpg)

**Step5**: Find `ios/AppController.mm`, add necessary code for Facebook iOS SDK:
- Add header:

```

#import <FacebookSDK/FacebookSDK.h>

```

- Add the following method in the `@implementation` section:

```
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [FBSession.activeSession handleOpenURL:url];
}
```

- Insert `[FBAppCall handleDidBecomeActive];` in `applicationDidBecomeActive:` function:

```
- (void)applicationDidBecomeActive:(UIApplication *)application {
[FBAppCall handleDidBecomeActive];
cocos2d::Director::getInstance()->resume();
}
```

#### Add PluginFacebook in your project
Because `Facebook SDK for Cocos2d-x` is based on Plugin-x, you need to add PluginFacebook into Plugin-x.

**Step1**: Right click `Plugin-x`, select `addFiles to "Plugin-x"`, then add `plugin/plugins/facebook/proj.ios/PluginFacebook.xcodeproj`.

**Step3**: Click `HelloPlugins`, then `Target`->`HelloPlugins`->`Build Phases`. Then click `+` button of `Link Binary With Libraries` list to add `libPluginFacebook.a`.

![](11/add_facebook_binary_lib.jpg)

<!--#### Integrate facebook in the lua-bindings
For facebook using in the lua ,we use `HelloPluginsLua` for an example.Except the setting steps introduced in the `HelloPlugins`,`HelloPluginsLua` has some special steps as follows:
**Step1**: open the `plugin/samples/HelloPluginsLua/frameworks/runtime-src/proj.ios_mac/HelloPluginsLua.xcodeproj`,add the `PluginFacebook.xcodeproj` in the `Plugins`
![](11/add_facebook_project_for_lua.jpg)
**Step2**: Add related lua-bindins files to the project
![](11/lua_bindings_for_facebook.jpg)
**Step3**: Find `Classes` folder, add lua-bindings related header files in `AppDelegate.cpp`:
```
#include "lua_cocos2dx_pluginx_auto.hpp"
#include "lua_pluginx_manual_callback.h"
#include "lua_pluginx_manual_protocols.h"
```
**Step4**: As the following code snippet, register lua-bindings code in `AppDelegate::applicationDidFinishLaunching`function of `AppDelegate.cpp`. **Notice**: Please pay attention to the location of the code.
```
bool AppDelegate::applicationDidFinishLaunching()
{
...
auto engine = LuaEngine::getInstance();
ScriptEngineManager::getInstance()->setScriptEngine(engine);
...
//register custom function
auto luaState = stack->getLuaState();
lua_getglobal(luaState, "_G");
register_all_pluginx_protocols(luaState);
register_all_pluginx_manual_callback(luaState);
register_all_pluginx_manual_protocols(luaState);
sc->start();
...
engine->executeScriptFile(ConfigParser::getInstance()->getEntryFile().c_str());
return true;
}
```
**Step5**:Select `TARGETS`->`HelloPluginsLua iOS`->`Build Phases`,then click `+` to add `New Run Script Build Phase` to copy some basic script.The related setting in the `HelloPluginsLua` is as follow:
![](11/xcode_copy_src_script.jpg)
-->
### Integrate Facebook SDK for Cocos2d-x on Android

#### Add PluginFacebook in your project

For android platform,you only need to make a few modifications to the Android project before you can use Facebook SDK.We also use `HelloPlugins` for example.

**Step1**: Add app name and app id in `/plugin/samples/HelloPlugins/proj.android/res/strings.xml`:

```
<string name="app_name">HelloPlugins</string>
<string name="app_id">641876029265874</string>
```

**Step2**: Add the following code snippet in `plugin/samples/HelloPlugins/proj.android/AndroidManifest.xml`:

```
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/app_id" />
<activity android:name="com.facebook.LoginActivity" />
<provider android:authorities="com.facebook.app.NativeAppCallContentProvider1450063488603945"
android:name="com.facebook.NativeAppCallContentProvider"
android:exported="true"/>
```

**Step3**: Add Plugin-x link lib in `plugin/samples/HelloPlugins/proj.android/jni/Android.mk`:

```
LOCAL_WHOLE_STATIC_LIBRARIES += cocos2dx_static \
PluginProtocolStatic
include $(BUILD_SHARED_LIBRARY)
$(call import-module,plugin/protocols/proj.android/jni)
```

**Step4**: Add the following code snippet in `plugin/samples/HelloPlugins/proj.android/jni/hellocpp/main.cpp`:

```
#include "PluginJniHelper.h"
void cocos_android_app_init (JNIEnv* env, jobject thiz) {
LOGD("cocos_android_app_init");
AppDelegate *pAppDelegate = new AppDelegate();
JavaVM* vm;
env->GetJavaVM(&vm);
PluginJniHelper::setJavaVM(vm);
}
```

**Step5**: Add the following code snippet in `plugin/samples/HelloPlugins/proj.android/project.properties`:

```
android.library.reference.2=../../../plugins/facebook/proj.android/DependProject
```

**Step6**: Set Java build path by the Eclipse,right click the `HelloPlugins`,choose `Properties`->`Java Build Path`->`Libaries` to add JAR,

![](11/android_eclipse_add_lib.jpg)

**NOTE**:If you don't find these JAR files,you should run `publish.sh` in the `plugin/tools/publish.sh`. if you update the facebook sdk, you also run this shell script.

**Step7**: Add the following code snippet in `plugin/samples/HelloPlugins/proj.android/src/org/cocos2dx/HelloPlugins/AppActivity.java`:

```
import org.cocos2dx.plugin.PluginWrapper;
import org.cocos2dx.plugin.FacebookWrapper;
import android.content.Intent;
import android.os.Bundle;
public class AppActivity extends Cocos2dxActivity {
//...
@Override
public Cocos2dxGLSurfaceView onCreateView() {
Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
// TestCpp should create stencil buffer
glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);
PluginWrapper.init(this);
PluginWrapper.setGLSurfaceView(glSurfaceView);
FacebookWrapper.onCreate(this);
return glSurfaceView;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(!PluginWrapper.onActivityResult(requestCode, resultCode, data))
{
super.onActivityResult(requestCode, resultCode, data);
}
FacebookWrapper.onAcitivityResult(requestCode, resultCode, data);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
FacebookWrapper.onSaveInstanceState(outState);
}
//...
}
```

#### Integrate facebook in the lua-bindings

Also using `HelloPluginsLua` for an example, you can refer to the setting steps introduced in the `HelloPlugins` and `Integrate facebook in the lua-bindings` except the copy basic script files.

Add the following code snippet in `copy_resources` section of `plugin/samples/HelloPluginsLua/frameworks/runtime-src/proj.android/build-cg.json`:

```
"must_copy_resources": [
{
"from": "../../../../../../cocos/scripting/lua-bindings/script/",
"to": "src/cocos"
},
{
"from": "../../../../../luabindings/script/",
"to": "src/cocos/lua_plugin"
},
...
]
```

You can use Cocos2d-x built-in tool - Cocos Console to package your project into an apk file, Run the following command in terminal or commandline under your project folder:

```
cocos compile -p android -j 4
```

### Use Facebook SDK in the codes
`cocos2d::plugin::FacebookAgent` is a singleton class that encapsulates the methods of Facebook SDK Beta2 for Cocos2d-x. Before doing anything else, you need to initialize the instance first by the `cocos2d::plugin::FacebookAgent::getInstance`.

The API list of `cocos2d::plugin::FacebookAgent` as follows:

|Name|Description|
|----|-----------|
|getInstance|Initialize the SDK, and return the instance of `cocos2d::plugin::FacebookAgent`. Required before doing anything else.|
|destroyInstance|Destroy the instance of `cocos2d::plugin::FacebookAgent`.|
|api|Call the [Facebook Graph API](http://developers.facebook.com/docs/graph-api) to find out about the user or act on his/her behalf.|
|dialog|Trigger different forms of Facebook created UI dialogs, such as the Share Dialog for one-to-many sharing on Facebook, or the Message Dialog for sending messages to friends. |
|canPresentDialog|Check whether it can trigger a particular form of Facebook created UI dialog based on the current user's device environment.|
|appRequest|Trigger the [Request](http://developers.facebook.com/docs/reference/dialogs/requests/) dialog to send a request to one or more of friends from a game.|
|login|Ask a user to authorize your app, or to grant additional authorizations.|
|logout|Log a user entirely out of Facebook.|
|isLoggedIn|Check whether a user is currently logged in and has authorized your app.|
|getUserId|Get the Facebook user ID of the currently logged in user.|
|getAccessToken|Get the access token granted to your application by current user.|
|activateApp|Report the launch of the app, for integration with Facebook app ads. More details at [App Events](http://developers.facebook.com/docs/platforminsights/appevents). |
|logEvent|Report an app event, for integration with Facebook app ads. More details at [App Events](http://developers.facebook.com/docs/platforminsights/appevents). |
|logPurchase|Report a purchase event, for integration with Facebook app ads. More details at [App Events](http://developers.facebook.com/docs/platforminsights/appevents). |

After integrating the facebook sdk into the project, we could use the api of `cocos2d::plugin::FacebookAgent` to realize the some functions.For example:

```c++
//login facebook
FacebookAgent::getInstance()->login([=](int ret, std::string& msg){
CCLOG("msg is %s", msg.c_str());
});

//is login
if(FacebookAgent::getInstance()->isLoggedIn())
{
CCLOG("already login in");
}

//login with permission
std::string permissions = "create_event,create_note,manage_pages,publish_actions,user_about_me";
FacebookAgent::getInstance()->login(permissions, [=](int ret, std::string& msg){
CCLOG("msg is %s", msg.c_str());
});

//request api
std::string path = "/me/photos";
FacebookAgent::FBInfo params;
params["url"] = "http://files.cocos2d-x.org/images/orgsite/logo.png";
FacebookAgent::getInstance()->api(path, FacebookAgent::HttpMethod::Post, params, [=](int ret, std::string& msg){
if (0 == ret) {
callbackInfo->setString(msg.c_str());
}
});

//share open grap
FacebookAgent::FBInfo params;
params.insert(std::make_pair("dialog", "share_open_graph"));
params.insert(std::make_pair("action_type", "cocosx_facebook:share"));
params.insert(std::make_pair("preview_property_name", "cocos_document"));
params.insert(std::make_pair("title", "Cocos2d-x Game Engine"));
params.insert(std::make_pair("image", "http://files.cocos2d-x.org/images/orgsite/logo.png"));
params.insert(std::make_pair("url", "http://cocos2d-x.org/docs/catalog/en"));
params.insert(std::make_pair("description", "cocos document"));

if (FacebookAgent::getInstance()->canPresentDialogWithParams(params))
{
FacebookAgent::getInstance()->dialog(params, [=](int ret ,std::string& msg){
CCLOG("%s", msg.c_str());
});
}
else
{
CCLOG("Can't open dialog for share_open_graph");
}
```
```lua
--login facebook
plugin.FacebookAgent:getInstance():login(function(ret, msg)
print(string.format("type is %d, msg is %s", ret, msg))
end
)
--is login
if plugin.FacebookAgent:getInstance():isLoggedIn() then
print("already login in")
end
--login with permission
local permissions = "create_event,create_note,manage_pages,publish_actions,user_about_me"
plugin.FacebookAgent:getInstance():login(permissions, function(ret, msg)
self.infoLabel:setString(msg)
end)
--request api
local path = "/me/photos"
local params = {url = "http://files.cocos2d-x.org/images/orgsite/logo.png"}
plugin.FacebookAgent:getInstance():api(path, plugin.FacebookAgent.HttpMethod.POST, params, function(ret, msg)
if 0 == ret then
self.infoLabel:setString(msg)
end
end)
--share open grap
local params = {
dialog = "share_open_graph",
action_type = "cocostestmyfc:share",
preview_property_name = "cocos_document",
title = "Cocos2dx-lua Game Engine",
image = "http://files.cocos2d-x.org/images/orgsite/logo.png",
url = "http://cocos2d-x.org/docs/catalog/en",
description = "cocos document",
}
if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then
plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg)
print(msg)
end)
else
print("Can't open dialog for share_open_graph")
end
```

For more detail use of `cocos2d::plugin::FacebookAgent`,you can refer to `TestFacebookUser` and `TestFacebookShare` in the `plugin/samples/HelloPlugins` for cpp,and refer to `TestFBUserScene` and `TestFBShareScene` in the `plugin/samples/HelloPluginsLua` for lua

**Note**:To use facebook's functions you should install the `facebook` application and to use facebook's share functions, you must install `Messenger` application.

0 comments on commit 4221197

Please sign in to comment.