1. 程式人生 > >標題:如何使用ShareSDK實現Cocos2d-x的Android/iOS分享與授權

標題:如何使用ShareSDK實現Cocos2d-x的Android/iOS分享與授權

Cocos2DX 簡介

Cocos2d-x是一套成熟的開源跨平臺遊戲開發框架。其引擎提供了圖形渲染、GUI、音訊、網路、物理、使用者輸入等豐富的功能,被廣泛應用於遊戲開發及互動式應用的構建。引擎的核心採用C++ 編寫,支援使用C++、Lua或者JavaScript進行開發。同時Cocos2d-x可以適配IOS、Android、HTML5、Windows和Mac系統。

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

Cocos2d-x整合ShareSDK過程如下:

  • 產品主頁網址:http://www.mob.com/product/sharesdk
  • 官方外掛地址:https://github.com/MobClub/New-C2DX-For-ShareSDK

Android 整合

首先下載官方外掛,下載完畢之後需要做如下幾步工作

  1. 把ShareSDK的cocos2dx的proj.android-studio專案裡的libs包複製到你的專案裡,除了armeabi目錄不用複製其他都要。

  2. 把ShareSDK的cocos2dx的New-C2DX-For-ShareSDK專案裡的Classes目錄下的檔案都複製到你的專案裡的Classes目錄下。

  3. 在jni/Android.mk新增下面程式碼來引入相關檔案,如:

    ../../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標籤,配置如下的程式碼

    compile project(':libcocos2dx')
    
  5. 在主activity裡(一般在cocos專案的此目錄下面:\proj.android-studio\src\org\cocos2dx\cpp\AppActivity.java)的onCreate方法裡新增ShareSDKUtils.prepare()方法。

    protected void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            ShareSDKUtils.prepare();
    }
    
  1. 各個平臺的配置方式:平臺的配置在libcocos2dx這個依賴工程內,工程根目錄下邊有一個MobSDK.gradle檔案,寫法示例如下邊的程式碼所示,使用者需要用自己申請到的Key來替換下文中的key。平臺的選擇也根據自己的需要來進行增加刪除。

    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專案中

  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;
        }
    }