如何使用ShareSDK實現Cocos2d-x的Android/iOS分享與受權

Cocos2DX 簡介

Cocos2d-x是一套成熟的開源跨平臺遊戲開發框架。其引擎提供了圖形渲染、GUI、音頻、網絡、物理、用戶輸入等豐富的功能,被普遍應用於遊戲開發及交互式應用的構建。引擎的核心採用C++ 編寫,支持使用C++、Lua或者JavaScript進行開發。同時Cocos2d-x能夠適配IOS、Android、HTML五、Windows和Mac系統。php

Cocos2d-x在中國及全球都有必定的市場份額,爲了給開發出來的遊戲增長知名度,更好的進行營銷,社交分享功能是必不可少的。可是所要分享的平臺針對全球不一樣的區域有不一樣的側重點,這就須要短期內接入多個社交平臺,可是每一個平臺的接入時間成本按天計算,多個平臺疊加在一塊兒的時間就很不樂觀。因此使用Cocos2d-x引擎的開發人員急需一種可以讓開發者快速接入受權、分享功能的SDK。java

Cocos2d-x集成ShareSDK過程以下:

Android 集成

首先下載官方插件,下載完畢以後須要作以下幾步工做android

  1. 把ShareSDK的cocos2dx的proj.android-studio項目裏的libs包複製到你的項目裏,除了armeabi目錄不用複製其餘都要。ios

  2. 把ShareSDK的cocos2dx的New-C2DX-For-ShareSDK項目裏的Classes目錄下的文件都複製到你的項目裏的Classes目錄下。c++

  3. 在jni/Android.mk添加下面代碼來引入相關文件,如:git

    ../../Classes/AppDelegate.cpp \
       ../../Classes/HelloWorldScene.cpp \
       ../../Classes/C2DXShareSDK/Android/ShareSDKUtils.cpp \
       ../../Classes/C2DXShareSDK/C2DXShareSDK.cpp \
       ../../Classes/C2DXShareSDK/Android/JSON/CCJSONConverter.cpp \
       ../../Classes/C2DXShareSDK/Android/JSON/cJSON/cJSON.c
    
    
    LOCAL_C_INCLUDES := $(LOCAL_PATH)/../../Classes \
    
       $(LOCAL_PATH)/../../Classes/C2DXShareSDK \
       $(LOCAL_PATH)/../../Classes/C2DXShareSDK/Android \
       $(LOCAL_PATH)/../../Classes/C2DXShareSDK/Android/JSON \
       $(LOCAL_PATH)/../../Classes/C2DXShareSDK/Android/JSON/cJSON
  4. 在proj.android-studio工程下,app目錄下,build.gradle文件內,尋找到dependencies標籤,配置以下的代碼github

    compile project(':libcocos2dx')
  5. 在主activity裏(通常在cocos項目的此目錄下面:\proj.android-studio\src\org\cocos2dx\cpp\AppActivity.java)的onCreate方法裏添加ShareSDKUtils.prepare()方法。sql

    protected void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            ShareSDKUtils.prepare();
    }
  1. 各個平臺的配置方式:平臺的配置在libcocos2dx這個依賴工程內,工程根目錄下邊有一個MobSDK.gradle文件,寫法示例以下邊的代碼所示,用戶須要用本身申請到的Key來替換下文中的key。平臺的選擇也根據本身的須要來進行增長刪除。api

    apply plugin: 'com.mob.sdk'
    MobSDK {
        appKey "moba6b6c6d6"
        appSecret "b89d2427a3bc7ad1aea1e1e8c1d36bf3"
    
        ShareSDK {
            //平臺配置信息
            devInfo {
                SinaWeibo {
                    id 1
                    sortId 1
                    appKey "568898243"
                    appSecret "38a4f8204cc784f81f9f0daaf31e02e3"
                    callbackUri "http://www.sharesdk.cn"
                    shareByAppClient true
                    enable true
                }
    
                QZone {
                    id 3
                    sortId 3
                    appId "100371282"
                    appKey "aed9b0303e3ed1e27bae87c33761161d"
                    shareByAppClient true
                    bypassApproval false
                    enable true
                }
    
                QQ {
                    id 7
                    sortId 7
                    appId "100371282"
                    appKey "aed9b0303e3ed1e27bae87c33761161d"
                    shareByAppClient true
                    bypassApproval false
                    enable true
                }
    
     			Wechat {
                    id 4
                    sortId 4
                    appId "wx4868b35061f87885"
                    appSecret "64020361b8ec4c99936c0e3999a9f249"
                    userName "gh_b0c6a9ca668a"
                    path "pages/index/index?id=mob"
                    withShareTicket true
                    miniprogramType 2
                    bypassApproval false
                    enable true
                }
    
                WechatMoments {
                    id 5
                    sortId 5
                    appId "wx4868b35061f87885"
                    appSecret "64020361b8ec4c99936c0e3999a9f249"
                    bypassApproval false
                    enable true
                }
    
                WechatFavorite {
                    id 6
                    sortId 6
                    appId "wx4868b35061f87885"
                    appSecret "64020361b8ec4c99936c0e3999a9f249"
                    bypassApproval false
                    enable true
                }
                
                Facebook {
                    id 8
                    sortId 8
                    appKey "1412473428822331"
                    appSecret "a42f4f3f867dc947b9ed6020c2e93558"
                    callbackUri "https://mob.com"
                    shareByAppClient true
                    enable true
                }
    
                Twitter {
                    id 9
                    sortId 9
                    appKey "viOnkeLpHBKs6KXV7MPpeGyzE"
                    appSecret "NJEglQUy2rqZ9Io9FcAU9p17omFqbORknUpRrCDOK46aAbIiey"
                    callbackUri "http://mob.com"
                    shareByAppClient true
                    enable true
                }
                
            }
        }
    }

iOS 集成

  1. 將下面紅色方框的資源文件拖到Cocos2d-x項目中android-studio

  2. 將SDK文件夾拖進項目(下載地址) 注意:請務必在上述步驟中選擇「Create groups for any added folders」單選按鈕組。若是你選擇「Create folder references for any added folders」,一個藍色的文件夾引用將被添加到項目而且將沒法找到它的資源。

  3. 添加必須的依賴庫

    • libc++.tbd
    • libz.tbd
    • libsqlite3.tbd

各社交平臺所需依賴庫:

新浪微博:

  • ImageIO.framework
  • Photos.framework

Instagram:

  • AssetsLibrary.framework
  • Photos.framework

美拍:

  • AssetsLibrary.framework

添加依賴庫的方法以下

  1. 配置UrlScheme和白名單等,各個社交平臺須要的配置能夠參考快速集成文檔中的URL Scheme和白名單配置項。

  2. 在項目工程的Info.plist 中如圖增長 MOBAppKey 和 MOBAppSecret 兩個字段

    在 MOBAppKey中 設置ShareSDK的appKey,若是還沒有在ShareSDK官網註冊過App,請移步到 登陸後臺 進行應用註冊也能夠點擊 連接 看裏面的操做步驟。

代碼實現

  • 初始化: 打開Classes目錄下邊的AppDelegate.cpp文件,直接拷貝粘貼代碼進行初始化工做。

    導入頭文件

    # include "C2DXShareSDK.h"

    初始化

    bool AppDelegate::applicationDidFinishLaunching()
        {
            //初始化ShareSDK
            this->initShareSDKConfig();
        }
        
        void AppDelegate::initShareSDKConfig()
        {
            //設置平臺配置
             //Platforms
             __Dictionary *totalDict = __Dictionary::create();
             
             //新浪微博
             __Dictionary *sinaWeiboConf= __Dictionary::create();
             sinaWeiboConf->setObject(__String::create("568898243"), "app_key");
             sinaWeiboConf->setObject(__String::create("38a4f8204cc784f81f9f0daaf31e0 2e3"), "app_secret");
             sinaWeiboConf->setObject(__String::create("http://www.sharesdk.cn"), "re direct_uri");
             stringstream sina;
             sina << cn::sharesdk::C2DXPlatTypeSinaWeibo;
             totalDict->setObject(sinaWeiboConf, sina.str());
             
             //微信
             __Dictionary *wechatConf = __Dictionary::create();
             wechatConf->setObject(__String::create("wx4868b35061f87885"), "app_id");
             wechatConf->setObject(__String::create("64020361b8ec4c99936c0e3999a9f249 "), "app_secret");
             stringstream wechat;
             wechat << cn::sharesdk::C2DXPlatTypeWechatPlatform;
             totalDict->setObject(wechatConf, wechat.str());
             
             //QQ
             __Dictionary *qqConf = __Dictionary::create();
             qqConf->setObject(__String::create("100371282"), "app_id");
             qqConf->setObject(__String::create("aed9b0303e3ed1e27bae87c33761161d"),  "app_key");
             stringstream qq;
             qq << cn::sharesdk::C2DXPlatTypeQQPlatform;
             totalDict->setObject(qqConf, qq.str());
             
             //Facebook
             __Dictionary *fbConf = __Dictionary::create();
             fbConf->setObject(__String::create("107704292745179"), "api_key");
             fbConf->setObject(__String::create("38053202e1a5fe26c80c753071f0b573"),  "app_secret");
             stringstream facebook;
             facebook << cn::sharesdk::C2DXPlatTypeFacebook;
             totalDict->setObject(fbConf, facebook.str());
             
             //Twitter 
             __Dictionary *twConf = __Dictionary::create();
             twConf->setObject(__String::create("LRBM0H75rWrU9gNHvlEAA2aOy"), "consumer_key");
             twConf->setObject(__String::create("gbeWsZvA9ELJSdoBzJ5oLKX0TU09UOwrzdGfo9Tg7DjyGuMe8G"), "consumer_secret");
             twConf->setObject(__String::create("http://www.mob.com"), "redirect_uri" ) ;
             stringstream twitter;
             twitter << cn::sharesdk::C2DXPlatTypeTwitter;
             totalDict->setObject(twConf, twitter.str());
             
             cn::sharesdk::C2DXShareSDK::registerAppAndSetPlatformConfig("moba6b6c6d6","b89d2427a3bc7ad1aea1e1e8c1d36bf3",totalDict);
        }

    以上平臺的app_key、app_secret等字段不一樣分享平臺可能不一樣,詳情可參考:《統一表》

  • 受權功能

    C2DXShareSDK::authorize(C2DXPlatTypeSinaWeibo, authResultHandler);

    authResultHandler是默認定製的一個回調類,也能夠本身寫一個新的回調類來替代此類

    //受權回調
    void authResultHandler(int seqId, cn::sharesdk::C2DXResponseState state, cn::sharesdk::C2DXPlatType platType, __Dictionary *result)
    {
        switch (state)
        {
            case cn::sharesdk::C2DXResponseStateSuccess:
            {
                log("Success");
                
                //輸出信息
                try
                {
                    __Array *allKeys = result -> allKeys();
                    allKeys->retain();
                    for (int i = 0; i < allKeys -> count(); i++)
                    {
                        __String *key = (__String *)allKeys -> getObjectAtIndex(i);
                        Ref *obj = result -> objectForKey(key -> getCString());
                        
                        log("key = %s", key -> getCString());
                        if (dynamic_cast<__String *>(obj))
                        {
                            log("value = %s", dynamic_cast<__String *>(obj) -> getCString());
                        }
                        else if (dynamic_cast<__Integer *>(obj))
                        {
                            log("value = %d", dynamic_cast<__Integer *>(obj) -> getValue());
                        }
                        else if (dynamic_cast<__Double *>(obj))
                        {
                            log("value = %f", dynamic_cast<__Double *>(obj) -> getValue());
                        }
                    }
                    allKeys->release();
                }
                catch(...)
                {
                    log("==============error");
                }
            }
                break;
            case cn::sharesdk::C2DXResponseStateFail:
            {
                log("Fail");
                //回調錯誤信息
                __Array *allKeys = result->allKeys();
                allKeys->retain();
                for (int i = 0; i < allKeys-> count(); i++)
                {
                    __String *key = (__String*)allKeys->getObjectAtIndex(i);
                    Ref *obj = result->objectForKey(key->getCString());
                    
                    log("key = %s", key -> getCString());
                    if (dynamic_cast<__String *>(obj))
                    {
                        log("value = %s", dynamic_cast<__String *>(obj) -> getCString());
                    }
                    else if (dynamic_cast<__Integer *>(obj))
                    {
                        log("value = %d", dynamic_cast<__Integer *>(obj) -> getValue());
                    }
                    else if (dynamic_cast<__Double *>(obj))
                    {
                        log("value = %f", dynamic_cast<__Double *>(obj) -> getValue());
                    }
                }
            }
                break;
            case cn::sharesdk::C2DXResponseStateCancel:
            {
                log("Cancel");
            }
                break;
            default:
                break;
        }
    }
  • 獲取用戶的信息

    受權以後,能夠經過以下的方法來獲取用戶信息。

    C2DXShareSDKC ::getUserInfo(C2DXPlatTypeSinaWeibo, getUserResultHandler);
  • 分享

  1. 在須要分享操做的代碼塊中進行構造分享參數,示例以下:

    __Dictionary *content = __Dictionary::create();
     content -> setObject(__String::create("分享文本"), "text");  // 分享文本
     content -> setObject(__String::create("HelloWorld.png"), "image");// 分享圖片
     content -> setObject(__String::create("測試標題"), "title"); // 分享標題
     content -> setObject(__String::create("http://www.mob.com"), "url"); // 分享url
     content -> setObject(__String::createWithFormat("%d", cn::sharesdk::C2DXContentTypeWebPage), "type"); /

    構造分享內容字段參數值請參考:《分享內容字段值表》

  2. 調用分享方法:

    //彈出菜單
    C2DXShareSDK::showShareMenu(NULL,content,100,100, shareContentResultHandler);// 第3,4個參數傳入 iPad 視圖要顯示的座標點,詳見API說明
    
    //無UI,直接分享
    C2DXShareSDK::shareContent(cn::sharesdk::C2DXPlatTypeSinaWeibo, content, shareContentResultHandler);
     
    //彈出編輯界面分享
    C2DXShareSDK::showShareView(cn::sharesdk::C2DXPlatTypeSinaWeibo, content, shareContentResultHandler);
  3. 設置分享回調方法 shareContentResultHandler,示例以下:

    //分享回調
    void shareContentResultHandler(int seqId, cn::sharesdk::C2DXResponseState state, cn::sharesdk::C2DXPlatType platType, __Dictionary *result)
    {
        switch (state)
        {
            case cn::sharesdk::C2DXResponseStateSuccess:
            {
                log("Success");
            }
                break;
            case cn::sharesdk::C2DXResponseStateFail:
            {
                log("Fail");
                //回調錯誤信息
                __Array *allKeys = result->allKeys();
                allKeys->retain();
                for (int i = 0; i < allKeys-> count(); i++)
                {
                    __String *key = (__String*)allKeys->getObjectAtIndex(i);
                    Ref *obj = result->objectForKey(key->getCString());
     
                    log("key = %s", key -> getCString());
                    if (dynamic_cast<__String *>(obj))
                    {
                        log("value = %s", dynamic_cast<__String *>(obj) -> getCString());
                    }
                    else if (dynamic_cast<__Integer *>(obj))
                    {
                        log("value = %d", dynamic_cast<__Integer *>(obj) -> getValue());
                    }
                    else if (dynamic_cast<__Double *>(obj))
                    {
                        log("value = %f", dynamic_cast<__Double *>(obj) -> getValue());
                    }
                }
            }
                break;
            case cn::sharesdk::C2DXResponseStateCancel:
            {
                log("Cancel");
            }
                break;
            default:
                break;
        }
    }
相關文章
相關標籤/搜索