cocos creator android和ios原生平台接入facebook登录和分享

本文重点介绍开发相关的内容,创建应用和应用配置请看官方文档。

官方文档:https://developers.facebook.com/docs(需要科学上网)

cocos creator原生平台接入facebook登录和分享,基本思路是用ts/js实现业务功能,在android/ios接入sdk,通过引擎桥接代码实现js与java/oc通信,完成整个业务流程。

本文对整个流程涉及的tsandroidios部分都有详细介绍。

一、ts部分

封装一个ts模块,处理与native接口交互

1、登录

1、登录接口

    /**
     * 登录
     */
    public static login() {
        if (cc.sys.isNative) {
            if (cc.sys.os == cc.sys.OS_ANDROID) {
                let className = "com/util/BridgeUtil";
                let methodName = "facebookLogin";
                let methodSignature = "()V";
                jsb.reflection.callStaticMethod(className, methodName, methodSignature);
            } else if (cc.sys.os == cc.sys.OS_IOS) {
                let className = "BridgeUtil";
                let methodName = "facebookLogin";
                jsb.reflection.callStaticMethod(className, methodName);
            }
        } else {
            let authInfo = '{"id":"1111111111111111","name":"Test","gender":"","email":"[email protected]","picture":"https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=xxx&height=50&width=50&ext=xxx","avatar":"https://graph.facebook.com/xxx/picture?type=large"}';
            cc.onFacebookLoginSuccess(authInfo);
        }
    }

2、登出接口

    /**
     * 登出
     */
    public static logout() {
        if (cc.sys.isNative) {
            if (cc.sys.os == cc.sys.OS_ANDROID) {
                let className = "com/util/BridgeUtil";
                let methodName = "facebookLogout";
                let methodSignature = "()V";
                jsb.reflection.callStaticMethod(className, methodName, methodSignature);
            } else if (cc.sys.os == cc.sys.OS_IOS) {
                let className = "BridgeUtil";
                let methodName = "facebookLogout";
                jsb.reflection.callStaticMethod(className, methodName);
            }
        }
    }

3、登录成功回调

/**
 * 登录成功
 */
cc.onFacebookLoginSuccess = function (authInfo) {
    console.log("onFacebookLoginSuccess authInfo = " + authInfo);
    //处理登录逻辑
};

4、登录取消回调

/**
 * 登录取消
 */
cc.onFacebookLoginCancel = function () {
    console.log("onFacebookLoginCancel");
};

5、登录错误回调

/**
 * 登录错误
 */
cc.onFacebookLoginError = function (error) {
    console.log("onFacebookLoginError error = " + error);
};

2、分享

1、分享类型

    /**
     * 分享类型
     */
    public static SHARE_TYPE = {
        /**
         * 链接
         */
        LINK: 0,
        /**
         * 图片
         */
        PHOTO: 1
    }

2、分享接口

    /**
     * 分享
     * @param shareType 分享类型 SHARE_TYPE
     * @param shareUrl 分享链接
     * @param imgPath 图片路径
     * @example
     * Facebook.share(Facebook.SHARE_TYPE.LINK, 'https://www.cocos.com/', '');
     */
    public static share(shareType: number, shareUrl: string, imgPath: string) {
        let data = {
            shareType: shareType,
            shareUrl: shareUrl,
            imgPath: imgPath
        };
        let shareInfo = JSON.stringify(data);
        console.log('Facebook share shareInfo = ' + shareInfo);

        if (cc.sys.isNative) {
            if (cc.sys.os == cc.sys.OS_ANDROID) {
                let className = "com/util/BridgeUtil";
                let methodName = "facebookShare";
                let methodSignature = "(Ljava/lang/String;)V";
                jsb.reflection.callStaticMethod(className, methodName, methodSignature, shareInfo);
            } else if (cc.sys.os == cc.sys.OS_IOS) {
                let className = "BridgeUtil";
                let methodName = "facebookShare:";
                jsb.reflection.callStaticMethod(className, methodName, shareInfo);
            }
        } else {
            cc.onFacebookShareSuccess('test');
        }
    }
}

二、android部分

1、登录

官方文档:https://developers.facebook.com/docs/facebook-login/android(需要科学上网)

1、集成 Facebook SDK

使用maven集成
1、在您的项目中,打开 your_app > Gradle Scripts > build.gradle (Project),确保下列存储库都添加到 buildscript { repositories {}} 中:

jcenter() 

2、在您的项目中,打开 your_app > Gradle Scripts > build.gradle (Module: app) 并将下列执行语句添加到 dependencies{} 部分,以便依赖于最新版的 Facebook 登录 SDK:

implementation 'com.facebook.android:facebook-login:[5,6)'

3、构建项目。

2、编辑资源和清单

1、打开 /app/res/values/strings.xml 文件。
2、添加如下所示的代码:

<string name="facebook_app_id" translatable="false">{你的应用id}</string>
<string name="fb_login_protocol_scheme" translatable="false">fb{你的应用id}</string>

3、打开 /app/manifest/AndroidManifest.xml 文件。
4、在 application 元素后添加以下 uses-permission 元素:

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

5、在 application 元素中添加以下 meta-data 元素、一个针对 Facebook 的 activity 元素以及一个针对 Chrome 自定义选项卡的 activity 元素和意向筛选条件:

<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:label="@string/app_name" />
<activity
    android:name="com.facebook.CustomTabActivity"
    android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="@string/fb_login_protocol_scheme" />
    </intent-filter>
</activity>

3、java编码

1、封装一个单例类,处理与Facebook SDK交互

    private static String TAG = "FacebookSdk";
    private static FacebookSdk mInstance = null;
    private Activity mActivity = null;
    private CallbackManager mCallbackManager = null;

    public static FacebookSdk getInstance() {
        if (null == mInstance) {
            mInstance = new FacebookSdk();
        }
        return mInstance;
    }

2、监听 onActivityResult 回调

    /**
     *  监听 onActivityResult
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i(TAG, "onActivityResult data = " + data.toString());

        if (mCallbackManager != null) {
            mCallbackManager.onActivityResult(requestCode, resultCode, data);
        }
    }

3、初始化单例

    /**
     *  初始化
     */
    public void initSdk(Activity activity) {
        Log.i(TAG, "initSdk");

        mActivity = activity;
        mCallbackManager = CallbackManager.Factory.create();

        initLogin();
        //initShare();
    }
    /**
     *  初始化登录
     */
    private void initLogin() {
        Log.i(TAG, "initLogin");

        LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                Log.e(TAG, "login onSuccess loginResult = " + loginResult.toString());

                //获取授权信息
                requestAuthInfo();
            }

            @Override
            public void onCancel() {
                Log.e(TAG, "login onCancel");

                //通知js
                final String eval = String.format("cc.onFacebookLoginCancel()");
                Cocos2dxHelper.runOnGLThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Cocos2dxJavascriptJavaBridge.evalString(eval);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

            @Override
            public void onError(FacebookException error) {
                Log.e(TAG, "login onError error = " + error.toString());

                //通知js
                final String eval = String.format("cc.onFacebookLoginError('%s')", error.toString());
                Cocos2dxHelper.runOnGLThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Cocos2dxJavascriptJavaBridge.evalString(eval);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

4、登录

    /**
     *  登录
     */
    public void login() {
        Log.i(TAG, "login");

        if (isAuthorization()) {
            //已经授权
            requestAuthInfo();
            return;
        }

        Collection<String> permissions = Arrays.asList("public_profile", "email");
        LoginManager.getInstance().logInWithReadPermissions(mActivity, permissions);
    }

5、是否授权

    /**
     *  是否授权
     */
    private boolean isAuthorization(){
        AccessToken accessToken = AccessToken.getCurrentAccessToken();
        if (accessToken == null) {
            return false;
        }

        return !accessToken.isExpired();
    }

6、获取授权信息

    /**
     *  获取授权信息
     */
    private void requestAuthInfo() {
        Log.i(TAG, "requestAuthInfo");

        AccessToken accessToken = AccessToken.getCurrentAccessToken();
        GraphRequest graphRequest = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject object, GraphResponse response) {
                Log.e(TAG, "requestAuthInfo onCompleted object = " + object.toString() + " response = " + response.toString());

                if (response.getError() != null) {
                    //授权错误
                    //通知js
                    final String eval = String.format("cc.onFacebookLoginError('%s')", response.getError().getErrorMessage());
                    Cocos2dxHelper.runOnGLThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Cocos2dxJavascriptJavaBridge.evalString(eval);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                    return;
                }

                //id:1565455221565
                String id = object.optString("id");
                //昵称:Zhang San
                String name = object.optString("name");
                //性别:比如 male (男)  female (女)
                String gender = object.optString("gender");
                //邮箱:比如:[email protected]
                String email = object.optString("email");
                //头像
                String picture = "";
                JSONObject objPicture = object.optJSONObject("picture");
                if (objPicture != null) {
                    JSONObject objPictureData = objPicture.optJSONObject("data");
                    if (objPictureData != null) {
                        picture = objPictureData.optString("url");
                    }
                }
                //头像
                String avatar = String.format("https://graph.facebook.com/%s/picture?type=large", id);
                String authInfo = String.format("{\"id\":\"%s\",\"name\":\"%s\",\"gender\":\"%s\",\"email\":\"%s\",\"picture\":\"%s\",\"avatar\":\"%s\"}",
                        id, name, gender, email, picture, avatar);

                //通知js
                final String eval = String.format("cc.onFacebookLoginSuccess('%s')", authInfo);
                Cocos2dxHelper.runOnGLThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Cocos2dxJavascriptJavaBridge.evalString(eval);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });

        Bundle param = new Bundle();
        param.putString("fields", "id,name,gender,email,picture");
        graphRequest.setParameters(param);
        graphRequest.executeAsync();
    }

7、登出

    /**
     *  登出
     */
    public void logout() {
        Log.i(TAG, "logout");

        LoginManager.getInstance().logOut();
    }

8、初始化Facebook SDK
MainActivityonCreate函数调用FacebookSdk.getInstance().initSdk(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onCreate(savedInstanceState);
        
        //...

        //初始化Facebook SDK
        FacebookSdk.getInstance().initSdk(this);
        
        //...
    }

9、监听onActivityResult
MainActivityonActivityResult函数调用FacebookSdk.getInstance().onActivityResult(requestCode, resultCode, data);

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        //...
        
        FacebookSdk.getInstance().onActivityResult(requestCode, resultCode, data);
        
        //...
    }

2、分享

官方文档:https://developers.facebook.com/docs/sharing/android(需要科学上网)

1、集成 Facebook SDK

使用maven集成
1、在您的项目中,打开 your_app > Gradle Scripts > build.gradle (Project),确保下列存储库都添加到 buildscript { repositories {}} 中:

jcenter() 

2、在您的项目中,打开 your_app > Gradle Scripts > build.gradle (Module: app) 并将下列执行语句添加到 dependencies{} 部分,以便依赖于最新版的 Facebook 分享 SDK:

implementation 'com.facebook.android:facebook-share:[5,6)'

3、构建项目。

2、编辑清单

1、打开 /app/manifest/AndroidManifest.xml 文件。
2、在 application 元素中添加以下 ContentProvider 元素:

<provider
    android:name="com.facebook.FacebookContentProvider"
    android:authorities="com.facebook.app.FacebookContentProvider{你的应用id}"
    android:exported="true" />

3、java编码

1、封装一个单例类,处理与Facebook SDK交互
在单例类中添加以下成员变量

    private ShareDialog mShareDialog = null;

2、初始化
在单例类的initSdk中调用initShare

    /**
     *  初始化分享
     */
    private void initShare() {
        Log.i(TAG, "initShare");

        mShareDialog = new ShareDialog(mActivity);
        mShareDialog.registerCallback(mCallbackManager, new FacebookCallback<Sharer.Result>() {
            @Override
            public void onSuccess(Sharer.Result result) {
                Log.e(TAG, "share onSuccess result = " + result.toString());

                //通知js
                final String eval = String.format("cc.onFacebookShareSuccess('%s')", result.toString());
                Cocos2dxHelper.runOnGLThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Cocos2dxJavascriptJavaBridge.evalString(eval);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

            @Override
            public void onCancel() {
                Log.e(TAG, "share onCancel");

                //通知js
                final String eval = String.format("cc.onFacebookShareCancel()");
                Cocos2dxHelper.runOnGLThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Cocos2dxJavascriptJavaBridge.evalString(eval);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

            @Override
            public void onError(FacebookException error) {
                Log.e(TAG, "share onError error = " + error.toString());

                //通知js
                final String eval = String.format("cc.onFacebookShareError('%s')", error.toString());
                Cocos2dxHelper.runOnGLThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Cocos2dxJavascriptJavaBridge.evalString(eval);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
            }
        });
    }

3、分享

    /**
     *  分享
     */
    public void share(String shareInfo) {
        Log.i(TAG, "share shareInfo = " + shareInfo);

        try {
            JSONObject json = new JSONObject(shareInfo);
            int shareType = json.getInt("shareType");
            String shareUrl = json.getString("shareUrl");
            String imgPath = json.getString("imgPath");

            if (shareType == 0) {
                //链接
                if (ShareDialog.canShow(ShareLinkContent.class)) {
                    ShareLinkContent content = new ShareLinkContent.Builder()
                            .setContentUrl(Uri.parse(shareUrl))
                            .build();
                    mShareDialog.show(content);
                }
            } else if (shareType == 1) {
                //图片
                if (ShareDialog.canShow(SharePhotoContent.class)) {
                    Bitmap img = BitmapFactory.decodeFile(imgPath);
                    SharePhoto photo = new SharePhoto.Builder()
                            .setBitmap(img)
                            .build();
                    SharePhotoContent content = new SharePhotoContent.Builder()
                            .addPhoto(photo)
                            .build();
                    mShareDialog.show(content);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

三、ios部分

1、登录

官方文档:https://developers.facebook.com/docs/facebook-login/ios(需要科学上网)

1、集成 Facebook SDK

1、下载 iOS 版 Facebook SDK
下载 SDK,然后将归档文件解压到 ~/Documents/FacebookSDK
下载地址:https://github.com/facebook/facebook-ios-sdk/releases/latest/download/FacebookSDK_Dynamic.framework.zip

2、向 Xcode 项目添加登录工具包
1)打开应用的 Xcode 项目。
2)如果您的项目中没有 Frameworks(框架)组,请创建一个,方法是:在 Xcode 的项目导航器内右击您的项目,并选择 New Group(新建组)。
3)打开解压缩的 SDK 文件夹 (~/Documents/FacebookSDK)。
4)将 FBSDKCoreKitFBSDKLoginKit 框架文件拖放至项目的 Frameworks(框架)组中。
5)在显示的对话框中,选择 Copy items if needed(必要时复制项目),并点击 Finish(完成)。

2、配置项目

使用包含应用数据的 XML 代码片段配置信息属性列表文件(info.plist)。
1、右键点击 info.plist,然后选择 作为源代码打开。
2、将下列 XML 代码片段复制并粘贴到文件正文中 (...)。

    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>fb{你的应用id}</string>
            </array>
        </dict>
    </array>
    <key>FacebookAppID</key>
    <string>{你的应用id}</string>
    <key>FacebookDisplayName</key>
    <string>{你的应用名称}</string>

3、如要使用任何 Facebook 对话框(例如,登录、分享、应用邀请等),以便从您的应用切换至 Facebook 应用,则您应用程序的 info.plist 还需包含:...

    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>fbapi</string>
        <string>fbapi20130214</string>
        <string>fbapi20130410</string>
        <string>fbapi20130702</string>
        <string>fbapi20131010</string>
        <string>fbapi20131219</string>
        <string>fbapi20140410</string>
        <string>fbapi20140116</string>
        <string>fbapi20150313</string>
        <string>fbapi20150629</string>
        <string>fbapi20160328</string>
        <string>fbauth</string>
        <string>fb-messenger-share-api</string>
        <string>fbauth2</string>
        <string>fbshareextension</string>
    </array>

3、oc编码

1、封装一个单例类,处理与Facebook SDK交互

/**
 结果类型
 */
typedef NS_ENUM(NSInteger, ResultType) {
    ResultTypeLoginSuccess,    //登录成功
    ResultTypeLoginCancel,    //登录取消
    ResultTypeLoginError,    //登录错误
    ResultTypeShareSuccess,    //分享成功
    ResultTypeShareCancel,    //分项取消
    ResultTypeShareError,    //分享错误
};

@interface FacebookSdk() <FBSDKSharingDelegate> {
    
}

@property (nonatomic, strong) RootViewController *viewController;

@property (nonatomic, strong) FBSDKLoginManager *loginManager;

@end

@implementation FacebookSdk

#pragma mark - 单例方法

static FacebookSdk *mInstace = nil;

+ (instancetype)getInstance {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mInstace = [[FacebookSdk alloc] init];
    });
    return mInstace;
}

2、初始化单例

#pragma mark - 初始化

/**
 初始化
 */
- (void)initSdk:(RootViewController *)viewController {
    NSLog(@"%s", __FUNCTION__);
    
    self.viewController = viewController;
    
    [self initLogin];
    //[self initShare];
}

#pragma mark - 登录

/**
 初始化登录
 */
- (void)initLogin {
    NSLog(@"%s", __FUNCTION__);
    
    self.loginManager = [[FBSDKLoginManager alloc] init];
}

3、登录

/**
 登录
 */
- (void)login {
    NSLog(@"%s", __FUNCTION__);
    
    if ([self isAuthorization]) {
        //已经授权
        [self requestAuthInfo];
        return;
    }
    
    [self.loginManager logInWithPermissions:@[@"public_profile", @"email"]
                         fromViewController:self.viewController handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
        NSLog(@"%s, FBSDKLoginManagerLoginResult, result: %@, error: %@", __FUNCTION__, result, error);
        
        if (error) {
            //登录错误
            NSLog(@"%s, FBSDKLoginManagerLoginResult error", __FUNCTION__);
            
            [self notifyToJs:ResultTypeLoginError params:[NSString stringWithFormat:@"%ld", (long)error.code]];
            return;
        }
        
        if (result) {
            if (result.isCancelled) {
                //登录取消
                NSLog(@"%s, FBSDKLoginManagerLoginResult cancel", __FUNCTION__);
                
                [self notifyToJs:ResultTypeLoginCancel params:@"login cancel"];
                return;
            }
            
            //登录成功
            NSLog(@"%s, FBSDKLoginManagerLoginResult success", __FUNCTION__);
            
            //获取授权信息
            [self requestAuthInfo];
        }
    }];
}

4、是否授权

/**
 是否授权
 */
- (BOOL)isAuthorization {
    NSLog(@"%s", __FUNCTION__);
    
    FBSDKAccessToken *accessToken = [FBSDKAccessToken currentAccessToken];
    if (accessToken == nil) {
        return NO;
    }
    
    return !accessToken.isExpired;
}

5、获取授权信息

/**
 获取授权信息
 */
- (void)requestAuthInfo {
    NSLog(@"%s", __FUNCTION__);
    
    FBSDKAccessToken *accessToken = [FBSDKAccessToken currentAccessToken];
    NSDictionary *params = @{@"fields":@"id,name,gender,email,picture"};
    FBSDKGraphRequest *graphRequest = [[FBSDKGraphRequest alloc]
                                       initWithGraphPath:accessToken.userID
                                       parameters:params];
    [graphRequest startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                               id result,
                                               NSError *error) {
        NSLog(@"%s, FBSDKGraphRequestConnection, result: %@, error: %@", __FUNCTION__, result, error);
        
        if (error) {
            //授权错误
            NSLog(@"%s, FBSDKGraphRequestConnection error", __FUNCTION__);
            
            [self notifyToJs:ResultTypeLoginError params:[NSString stringWithFormat:@"%ld", (long)error.code]];
            return;
        }
        
        if (result) {
            //授权成功
            NSLog(@"%s, FBSDKGraphRequestConnection success", __FUNCTION__);
            
            NSString *NSid = [result objectForKey:@"id"];
            NSString *name = [result objectForKey:@"name"];
            NSString *gender = [result objectForKey:@"gender"];
            NSString *email = [result objectForKey:@"email"];
            NSString *picture = @"";
            NSDictionary *objPicture = [result objectForKey:@"picture"];
            if (objPicture) {
                NSDictionary *objPictureData = [objPicture objectForKey:@"data"];
                if (objPictureData) {
                    NSString *NSpictureDataUrl = [objPictureData objectForKey:@"url"];
                    if (NSpictureDataUrl) {
                        picture = NSpictureDataUrl;
                    }
                }
            }
            NSString *avatar = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=large", NSid];
            NSString *authInfo = [NSString stringWithFormat:@"{\"id\":\"%@\",\"name\":\"%@\",\"gender\":\"%@\",\"email\":\"%@\",\"picture\":\"%@\",\"avatar\":\"%@\"}",
                                 NSid, name, gender, email, picture, avatar];
            
            [self notifyToJs:ResultTypeLoginSuccess params:authInfo];
        }
    }];
}

6、登出

/**
 登出
 */
- (void)logout {
    NSLog(@"%s", __FUNCTION__);
    
    [self.loginManager logOut];
}

7、通知js

/**
 通知js
 @param resultType 类型
 @param params 透传参数
 */
- (void)notifyToJs:(ResultType)resultType params:(NSString *)params {
    NSLog(@"%s, resultType: %ld, params: %@", __FUNCTION__, (long)resultType, params);
    
    NSString *funcName = @"";
    switch (resultType) {
        case ResultTypeLoginSuccess:
            funcName = @"cc.onFacebookLoginSuccess";
            break;
        case ResultTypeLoginCancel:
            funcName = @"cc.onFacebookLoginCancel";
            break;
        case ResultTypeLoginError:
            funcName = @"cc.onFacebookLoginError";
            break;
        case ResultTypeShareSuccess:
            funcName = @"cc.onFacebookShareSuccess";
            break;
        case ResultTypeShareCancel:
            funcName = @"cc.onFacebookShareCancel";
            break;
        case ResultTypeShareError:
            funcName = @"cc.onFacebookShareError";
            break;
        default:
            funcName = nil;
            break;
    }
    
    if (funcName == nil) {
        NSLog(@"%s, error: %@", __FUNCTION__, @"funcName is nil");
        return;
    }
    
    if (params == nil) {
        params = @"";
    }
    
    NSString *eval = [NSString stringWithFormat:@"%@('%@')", funcName, params];
    const char *c_eval = [eval UTF8String];
    se::ScriptEngine::getInstance()->evalString(c_eval);
}

8、初始化Facebook SDK
AppController- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions函数调用[[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];[[FacebookSdk getInstance] initSdk:_viewController];

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

    //...
    
    //Facebook SDK
    [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    [[FacebookSdk getInstance] initSdk:_viewController];
    
    //...
    
    //run the cocos2d-x game scene
    app->start();
    
    return YES;
}

9、重写- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url options:(NSDictionary *)options函数
AppController添加以下代码

/**
 * Facebook SDK相关
 */
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
    BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
        openURL:url
        sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
        annotation:options[UIApplicationOpenURLOptionsAnnotationKey]
    ];
    
    // Add any custom logic here. return handled;
    return handled;
}

2、分享

官方文档:https://developers.facebook.com/docs/sharing/ios(需要科学上网)

1、集成 Facebook SDK

1、下载 iOS 版 Facebook SDK
2、向 Xcode 项目添加分享工具包
1)打开应用的 Xcode 项目。
2)将 FBSDKShareKit 框架文件拖放至项目的 Frameworks(框架)组中。
3)在显示的对话框中,选择 Copy items if needed(必要时复制项目),并点击 Finish(完成)。

2、oc编码

1、封装一个单例类,处理与Facebook SDK交互

2、初始化
在单例类的initSdk中调用initShare

/**
 初始化分享
 */
- (void)initShare {
    NSLog(@"%s", __FUNCTION__);
}

3、分享

/**
 分享
 @param shareInfo 分享信息
 */
- (void)share:(NSString *)shareInfo {
    NSLog(@"%s, shareInfo: %@", __FUNCTION__, shareInfo);
    
    NSData *data = [shareInfo dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSNumber *shareType = [dictionary objectForKey:@"shareType"];
    NSString *shareUrl = [dictionary objectForKey:@"shareUrl"];
    NSString *imgPath = [dictionary objectForKey:@"imgPath"];
    
    if ([shareType intValue] == 0) {
        //链接
        FBSDKShareLinkContent *content = [[FBSDKShareLinkContent alloc] init];
        content.contentURL = [NSURL URLWithString:shareUrl];
        
        [FBSDKShareDialog showFromViewController:self.viewController
                                     withContent:content
                                        delegate:self];
    } else if ([shareType intValue] == 1) {
        //图片
        UIImage *image = [[UIImage alloc] initWithContentsOfFile:imgPath];
        
        FBSDKSharePhoto *photo = [[FBSDKSharePhoto alloc] init];
        photo.image = image;
        photo.userGenerated = YES;
        
        FBSDKSharePhotoContent *content = [[FBSDKSharePhotoContent alloc] init];
        content.photos = @[photo];
        
        [FBSDKShareDialog showFromViewController:self.viewController
                                     withContent:content
                                        delegate:self];
    }
}

4、添加FBSDKSharingDelegate委托

#pragma mark - FBSDKSharingDelegate

/**
  Sent to the delegate when the share completes without error or cancellation.
 @param sharer The FBSDKSharing that completed.
 @param results The results from the sharer.  This may be nil or empty.
 */
- (void)sharer:(id<FBSDKSharing>)sharer didCompleteWithResults:(NSDictionary<NSString *, id> *)results {
    NSLog(@"%s, results: %@", __FUNCTION__, results);
    
    [self notifyToJs:ResultTypeShareSuccess params:@"share success"];
}

/**
  Sent to the delegate when the sharer encounters an error.
 @param sharer The FBSDKSharing that completed.
 @param error The error.
 */
- (void)sharer:(id<FBSDKSharing>)sharer didFailWithError:(NSError * _Nullable)error {
    NSLog(@"%s, error: %@", __FUNCTION__, error);
    
    [self notifyToJs:ResultTypeShareError params:[NSString stringWithFormat:@"%ld", (long)error.code]];
}

/**
  Sent to the delegate when the sharer is cancelled.
 @param sharer The FBSDKSharing that completed.
 */
- (void)sharerDidCancel:(id<FBSDKSharing>)sharer {
    NSLog(@"%s", __FUNCTION__);
    
    [self notifyToJs:ResultTypeShareCancel params:@"share cancel"];
}

代码可能粘贴不完全,具体的代码我托管到github了,有需要的童鞋可以自行去下载。
建议自己揣摩清楚之后再参考或者引入自己的项目,之所谓知其然也要知其所以然。
代码中基本都有注释,如果没看懂可以私信我,我这边可以为你讲解。
有写错或者不足的地方欢迎大家批评指出,一起学习进步。

github地址:https://github.com/lupeng-github/cocos_creator_facebook_sdk

你可能感兴趣的:(cocos,facebook,cocos2d,android,ios,facebook,cocos2d-js)