Link address :http://blog.csdn.net/yeungxuguang/article/details/18227153

This article from the :http://www.iteye.com/topic/1130694

With the rapid popularity of smart computers , There are a lot of smart games on the market now (ios,android,wp,==), Recently I joined the ranks of mobile game developers . choice cocos2d-x As our game engine … In the course of studying other mobile games, I found that , Many games have the function of microblog sharing , When you fight in the game and get good grades , Do you want to share it with your friends … Microblog sharing is undoubtedly a good choice .

My request is to be able to share Sina Weibo , Tencent micro-blog ,QZone. If it was before , You may download the sdk Implant accordingly . For those of us who are new to microblog sharing development , If there is an integrated framework , My ideal situation is , You just need to write weibo.share,weibo.follow,== Can solve the tedious analysis ,check Wait for the operation . Recommended by friends , I met ShareSDK.

ShareSDK Is for iOS、Android、WP8 Of APP A component that provides social functions , Developers just need to 10 Minutes to integrate into your own APP in , It not only supports such as QQ、 WeChat 、 Sina weibo 、 Tencent micro-blog 、 Kaixin 、 Renren.com 、 douban 、 Netease Weibo 、 Sohu Weibo 、facebook、twitter、google+ And other mainstream social platforms at home and abroad , There is also a strong statistical analysis management background , Can understand users in real time 、 information flow 、 Reflux rate 、 Communication effects and other data , Effectively guide the daily operation and promotion , Also for APP Introduce more social traffic .【 I copy the official introduce, Sorry for my laziness 】, Detailed introduction in http://sharesdk.cn/Index/production, Interested friends can refer to .

according to ShareSDK From the introduction we can see that he has provided a number of view, Customize ui And so on package, For tradition app, It provides a friendly interface and operation behavior , But because our project is cocos2d-x The interface of ,so… I'm not going to use the official package for this part . If you're not going to use your own ui, The official provides a custom method , Please refer to official sdk Tutorials provided .

Sharesdk Application process

Please login. http://sharesdk.cn And sign up for an account . 

After successful registration , Click... On the home page ” My application ” 

Because I've created it before , It's ok , Click the add button  

Select the platform and application name you need , Because I need support android,ios, So we created two applications , Namely PokerFaceAndroid, PokerFaceIOS To distinguish .

Choose an app , You will be in ” download SDK” At the bottom of it Appkey The words... , This is what you will use in the future key. Download the corresponding SDK spare .

Introduce Sina Weibo , Tencent micro-blog ,QZone Of these three platforms appkey How to apply

【 Sina weibo 】

Get into http://open.weibo.com/developers, Application and authentication of developer account , I will not repeat the details .

The verification process may take some time , Please take a moment , Look at the introduction below

Get into http://open.weibo.com/development/mobile

I'm gonna go ahead and create an app

Enter information about your app , Be careful , Choose the platform you need , And create . After creation, you can view the basic situation of the application in the management interface .

Write down the AppKey and AppSecret, Next, we provide sharesdk Use .

There's a pit here , If you follow the steps above to create an app , When you share, you will report an error error:redirect_uri_mismatch. The solution is to get into the application - Domain name binding in advanced information security settings .

thus ,sina Microblogging app This is the end of the application process ,sina The rule of Weibo is from the date of application 3 The audit can only be started in 10 days ,so, Let's write the code .

【 Tencent micro-blog 】

Just like Sina Weibo , Tencent Weibo has to do the same thing , Get into http://dev.t.qq.com/development/developer/

Fill in relevant information for audit and qualification verification .

After verification, click “ Create an ”

 

Fill in the relevant information according to the prompts

After submission , Get into “ Management Center ” You can see the basic information of our application

Tencent Micro blog is just like this happy The end of

【QZone】

Get into http://connect.qq.com/intro/login/, Click apply to join , After a series of applications , to examine , Operation of verification , Enter the management center

I'm gonna go ahead and create an app

here , We choose mobile apps

Complete the relevant information . I'm gonna go ahead and create an app , We can do that “ Management Center ” You can see the app we created .

thus , Registration of these three platforms , This is the end of the creation process .

【 Integration summary 】

Cocos2d-x Support multiple platforms , I won't go over it here , We need to be in andriod,ios The version supports microblog sharing function , Of course, for the sake of compatibility , I have to write win32 The implementation of the , however win32 It's implemented as an empty function , It means no operation .

Share on Weibo , About a few things

Share  
Focus on  
to grant authorization  
Cancel Authorization  
Get users id 
Get user nickname  
In addition, you need to customize the callback functions of the above behaviors

The header file SocialShare.h

+ expand source 
Defines such a header file , It can be provided to win32( Empty function ),android and ios Used

SocialShareWin32.cpp

+ expand source 
【android Integrate 】

Download the official sharesdk(android edition ), After decompression, we get the following file list

among sample This is a comprehensive example , It explains various usages , Children's shoes can be researched by themselves , Familiarity

Libs Directory is

among Global-Dependences Is a package that is globally dependent , Name is ShareSDK-Core.jar

Platforms The compressed package file in is used by various platforms sdk package

Unzip it ,copy You can use it in your own project

ShareSDK-GUI The directory is for one click sharing , We don't have... At the moment ,so, If you are interested in children's shoes, you can refer to relevant information by yourself

add to

Logic used to support authorization

And add the corresponding permissions

After setting up , If something goes wrong , succeed in inviting sb. http://bbs.sharesdk.cn/thread-45-1-1.html Query or leave a message .

I'm going to modify “ Lord activity.java”

+ expand source 
Next , have a look jni How to write the part

SocialShareAndroid.cpp

+ expand source 
Android Integrate sharesdk It's over

【xcode Integrate 】

Download the official sharesdk(ios edition ), After decompression, we get the following file list

Please refer to the official document for the detailed integration process , What we use framework I extracted it ,list as follows

Add dependency framework (Framework)

Open... In project settings Build Phases page , stay “Link Binary With Libraries” In a column , Click on the bottom left corner “+” Number ; Add the following libraries to the project in the pop-up window :

SystemConfiguration.framework

QuartzCore.framework

libicucore.dylib

libz.1.2.5.dylib

// The following description comes from official documents BEGIN

open *-Info.plist(* On behalf of your project name ). Add a new item to the configuration file URL types

( If it exists, it can not be created ), an URL types –URL Schemes, stay URL Schemes Next, add one for Sina Weibo and Facebook Authorized by the Scheme( If not, it will lead to Sina Weibo or Facebook Of SSO Authorization method cannot return application ). The format of sina is :sinaweibosso.2279784657, The following number segment is the one you applied for on Sina Weibo AppKey.Facebook Fill in the form of :fb107704292745179, The last number segment is where you are Facebook Applied AppKey

//from Official documents END

Import header file ShareSDK.h And initialize the App Information .

open AppController.mm file ,#import <ShareSDK/ShareSDK.h>

Add implementation functions

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation

{

return [ShareSDK handleOpenURL:url sourceApplication:sourceApplication annotation:annotation wxDelegate:self];

}

-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url

{

return [ShareSDK handleOpenURL:url wxDelegate:self];

}

SocialShareIOS.mm file

#include “SocialShare.h”

#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)

#include

#import <ShareSDK/ShareSDK.h>

SocialShare *SocialShare::m_sShare = NULL;

typedef struct WeiboUserInfo

{

std::string userID;

std::string userName;

}WeiboUserInfo;

std::map<ShareType, WeiboUserInfo> g_mapUserInfo;

bool g_bSocialShareInited = false;

void SocialShare::init()

{

if (!g_bSocialShareInited)

{

SocialShare::m_sShare = new SocialShare();

g_mapUserInfo.clear();

[ShareSDK registerApp:@"xx"]; // You registered sharesdk Of appkey

[ShareSDK connectSinaWeiboWithAppKey:@"xx" appSecret:@"xx" redirectUri:@"xx"];

[ShareSDK connectTencentWeiboWithAppKey:@"xx" appSecret:@"xx" redirectUri:@"xx"];

[ShareSDK connectQZoneWithAppKey:@"xx" appSecret:@"xx"];

g_bSocialShareInited = true;

}

}

void SocialShare::end()

{

delete SocialShare::m_sShare;

SocialShare::m_sShare = NULL;

}

ShareType getWeiboType(const char* strWeiboName)

{

ShareType type = ShareTypeAny;

if (!strWeiboName || strlen(strWeiboName)==0)

{

CCLog(“SocialShare::getWeiboType strWeiboName is null!”);

return type;

}

if (strcmp(strWeiboName, SOCIALSHARE_SINAWEIBO_NAME) == 0)

{

type = ShareTypeSinaWeibo;

}

else if (strcmp(strWeiboName, SOCIALSHARE_TENCENTWEIBO_NAME) == 0)

{

type = ShareTypeTencentWeibo;

}

else if (strcmp(strWeiboName, SOCIALSHARE_QZONE_NAME) == 0)

{

type = ShareTypeQQSpace;

}

return type;

}

void updateWeiboInfo(const char* strWeiboName)

{

ShareType type = getWeiboType(strWeiboName);

if (type == ShareTypeAny)

{

return;

}

[ShareSDK getUserInfoWithType:type authOptions:nil result:^(BOOL result, id userInfo, id error) {

if (result)

{

WeiboUserInfo tmp;

tmp.userName = [[userInfo nickname] UTF8String];

tmp.userID = [[userInfo uid] UTF8String];

g_mapUserInfo[type] = tmp;

}

else

{

g_mapUserInfo.erase(type);

}

}];

}

void SocialShare::weiboShare(const char* strWeiboName,const char* strTitle,const char* strText,const char* strImageDir,const char* strTitleUrl,const char* strImageUrl,const char* strSiteUrl)

{

ShareType type = getWeiboType(strWeiboName);

if (type == ShareTypeAny)

{

return;

}

char _strTitleUrl[128] = “\0″;

if (strTitleUrl && strlen(strTitleUrl)>0)

{

strcpy(_strTitleUrl, strTitleUrl);

}

NSString *imagePath = [NSString stringWithUTF8String:strImageDir];

id publicContent = [ShareSDK content:[NSString stringWithUTF8String:strText]  defaultContent:@”" image:[ShareSDK imageWithPath:imagePath] title:[NSString stringWithUTF8String:strTitle] url:[NSString stringWithUTF8String:_strTitleUrl] description:[NSString stringWithUTF8String:strText] mediaType:SSPublishContentMediaTypeText];

[ShareSDK shareContent:publicContent type:type authOptions:nil statusBarTips:YES result:^(ShareType type, SSPublishContentState state, id statusInfo, id error, BOOL end) {

if (state == SSPublishContentStateFail)

{

NSLog(@"weiboShare %@", [NSString stringWithFormat:@" Sharing failure %@", [error errorDescription]]);

}

if (state != 0)

{

doWeiboResultFunc(strWeiboName, 1, (int)state);

updateWeiboInfo(strWeiboName);

}

}];

}

void SocialShare::weiboFollowFriend(const char* strWeiboName, const char *strAccount)

{

ShareType type = getWeiboType(strWeiboName);

if (type == ShareTypeAny)

{

return;

}

[ShareSDK followUserWithType:type field:[NSString stringWithUTF8String:strAccount] fieldType:SSUserFieldTypeName authOptions:nil viewDelegate:nil result:^(SSResponseState state, id userInfo, id error) {

if (state == SSResponseStateFail)

{

NSLog(@”weiboShare %@”, [NSString stringWithFormat:@" Focus on failure %@", [error errorDescription]]);

}

if (state != 0)

{

doWeiboResultFunc(strWeiboName, 1, (int)state);

updateWeiboInfo(strWeiboName);

}

}];

}

void SocialShare::weiboAuth(const char* strWeiboName)

{

ShareType type = getWeiboType(strWeiboName);

if (type == ShareTypeAny)

{

return;

}

[ShareSDK authWithType:type options:nil result:^(SSAuthState state, id error) {

if (state == SSAuthStateFail)

{

NSLog(@"weiboShare %@", [NSString stringWithFormat:@" privilege grant failed %@", [error errorDescription]]);

}

if (state != 0)

{

doWeiboResultFunc(strWeiboName, 1, (int)state);

updateWeiboInfo(strWeiboName);

}

}];

}

void SocialShare::weiboRemoveAccount(const char* strWeiboName)

{

ShareType type = getWeiboType(strWeiboName);

if (type == ShareTypeAny)

{

return;

}

[ShareSDK cancelAuthWithType:type];

doWeiboResultFunc(strWeiboName, 4, 1);

updateWeiboInfo(strWeiboName);

}

std::string SocialShare::weiboGetUserId(const char* strWeiboName)

{

ShareType type = getWeiboType(strWeiboName);

std::map<ShareType, WeiboUserInfo>::iterator mi = g_mapUserInfo.find(type);

if (mi != g_mapUserInfo.end())

{

return mi->second.userID;

}

return “”;

}

std::string SocialShare::weiboGetUserName(const char* strWeiboName)

{

ShareType type = getWeiboType(strWeiboName);

std::map<ShareType, WeiboUserInfo>::iterator mi = g_mapUserInfo.find(type);

if (mi != g_mapUserInfo.end())

{

return mi->second.userName;

}

return “”;

}

#endif

thus ,IOS Part of the integration work has also been completed

We have to write some code to test it

The project name in your project .cpp In the initialization of

bool AppXXXXXX:applicationDidFinishLaunching() Add in

SocialShare::init();

void AppXXXXXX::exit() Add in

SocialShare::end();

//test weibo

SocialShare::shareSocialShare()->setWeiboResultNotifier(this, socialweibo_selector(MainMenuLayer::onweiboCallback));

CCMenuItemFont* weiboid              = CCMenuItemFont::create(a2u(“ Get Weibo id”).c_str(), this, menu_selector(MainMenuLayer::onweiboid));

CCMenuItemFont* weiboname      = CCMenuItemFont::create(a2u(“ Get microblog name ”).c_str(), this, menu_selector(MainMenuLayer::onweiboname));

CCMenuItemFont* weiboauth        = CCMenuItemFont::create(a2u(“ Weibo Authorization ”).c_str(), this, menu_selector(MainMenuLayer::onweiboauth));

CCMenuItemFont* removecount = CCMenuItemFont::create(a2u(“ Delete the account ”).c_str(), this, menu_selector(MainMenuLayer::onremovecount));

CCMenuItemFont* weibofollow = CCMenuItemFont::create(a2u(“ Weibo follows ”).c_str(), this, menu_selector(MainMenuLayer::onweibofollow));

CCMenuItemFont* weiboshare      = CCMenuItemFont::create(a2u(“ Share on Weibo ”).c_str(), this, menu_selector(MainMenuLayer::onweiboshare));

CCMenu* menu = CCMenu::create(weiboid, weiboname, weiboauth, removecount, weibofollow, weiboshare, NULL);

CCPoint menuPostion = menu->getPosition();

menu->setPosition(menuPostion.x, menuPostion.y + visibleSize.height * 0.1f);

menu->alignItemsVertically();

addChild(menu);

void MainMenuLayer::onweiboid(CCObject* sender)

{

CCLOG(“MainMenuLayer::onweiboid\t%s”, SocialShare::shareSocialShare()->weiboGetUserId(SOCIALSHARE_SINAWEIBO_NAME).c_str());

}

void MainMenuLayer::onweiboname(CCObject* sender)

{

CCLOG(“MainMenuLayer::onweiboname\t%s”, SocialShare::shareSocialShare()->weiboGetUserName(SOCIALSHARE_SINAWEIBO_NAME).c_str());

}

void MainMenuLayer::onweiboauth(CCObject* sender)

{

SocialShare::shareSocialShare()->weiboAuth(SOCIALSHARE_SINAWEIBO_NAME);

}

void MainMenuLayer::onremovecount(CCObject* sender)

{

SocialShare::shareSocialShare()->weiboRemoveAccount(SOCIALSHARE_SINAWEIBO_NAME);

}

void MainMenuLayer::onweibofollow(CCObject* sender)

{

SocialShare::shareSocialShare()->weiboFollowFriend(SOCIALSHARE_SINAWEIBO_NAME, a2u(“ Li Dongri -ldr123″).c_str());

}

void MainMenuLayer::onweiboshare(CCObject* sender)

{

string strFile = saveScreen(“xx.jpg”);

if (!strFile.empty())

{

SocialShare::shareSocialShare()->weiboShare(SOCIALSHARE_SINAWEIBO_NAME, a2u(“PokerFace test ”).c_str(),a2u(“ You can pay attention to it ,@ Li Dongri -ldr123 http://ldr123.mobi”).c_str(),strFile.c_str());

}

}

bool MainMenuLayer::onweiboCallback(const char* x, int y, int z)

{

CCLOG(“MainMenuLayer::onweiboCallback:%s,%d,%d”, x,y,z);

return true;

}

We see a2u() It's a function , This function is going to gb2312 String to utf8, In order to cocos2d-x Chinese is shown in the picture , Yes, it is iconv Realization , Please search related keywords for details “cocos2d-x iconv”

in addition , Provide saveScreen Code

// If it's for microblogging , best jpg...

std::string saveScreen(const char *fileName)

{

string strResult = “”;

bool bResult = false;

CCSize size = CCDirector::sharedDirector()->getWinSize();

CCRenderTexture* screen = CCRenderTexture::create(size.width, size.height);

CCScene* temp = CCDirector::sharedDirector()->getRunningScene();

screen->begin();

temp->visit();

screen->end();

CCImage *pImage = screen->newCCImage(true);

if (pImage)

{

strResult = CCFileUtils::sharedFileUtils()->getWritablePath() + fileName;

bResult = pImage->saveToFile(strResult.c_str(), true);

}

CC_SAFE_DELETE(pImage);

CC_SAFE_DELETE(screen);

if (bResult)

{

return strResult;

}

return “”;

}

wow , A lot of things , It's finally over , Happy compilation and debugging .

Postscript :

This time, weibo Share the integration journey , I feel a lot , Every time you see something new , I always think it's easy , It'll be done in minutes , But the real participation in the operation will find , All kinds of holes that need to be solved . Leave this blog for reference only . There may be some inappropriate or inaccurate words in the blog , Please ask Hai Han. . Also thanks sharesdk The official customer service patiently answers and offers suggestions , Thank you again for !

Last , If you are cocos2d-x Users , Also want to use sharesdk, So you're in the right place , Here is the solution to your troubles , Welcome technical discussion and exchange , The code fragment provided in the blog is enough to help understand and use , For coders , I can only “ ha-ha ” 了 .

my cocos2d-x Integrate sharesdk The journey ( turn ) More articles about

  1. Mob Social sharing and integration ShareSDK

    Then I share an article about using it by myself ShareSDK The notes , We have integrated SMSSDK Complete the function of SMS receiving verification code , Please refer to Mob And SMS verification Integration SMSSDK, How to integrate in the project SMSSDK The situation of ...

  2. iOS Integrate sharesdk Pit encountered

    Share Sina Weibo *** Share Sina Weibo *** Preface : The purpose of writing this is to record those who go through the pit , Go straight to the renderings first . Let's see if you encounter it, you should deal with it better , Because as soon as I saw this effect, I knew that it was very simple, not to share microblog . But ask for ...

  3. Integrate ShareSDK, After sharing success QQ And the possible reasons why spatial callbacks are not executed

    AndroidMainifest.xml As shown by the arrow in id And assets Next ShareSDK.xml Configured in QQ Of AppId It has to be the same .

  4. iOS Development --- Integrate ShareSDK Third party login 、 Share 、 Attention and other functions .

    (1) The official download ShareSDK IOS 2.9.6, Address :http://sharesdk.mob.com/Download (2) According to the actual situation , Introduce related libraries , Refer to official documentation . (3) In the project AppDel ...

  5. IOS Project integration ShareSDK Third party login 、 Share 、 Attention and other functions .

    (1) The official download ShareSDK iOS 2.8.8, Address :http://sharesdk.cn/ (2) According to the actual situation , Introduce related libraries , Refer to official documentation . (3) In the project AppDelegate In general, there are three ...

  6. IOS Project integration ShareSDK Third party login 、 Share 、 Attention and other functions ( spare )

    (1) The official download ShareSDK iOS 2.8.8, Address :http://sharesdk.cn/ (2) According to the actual situation , Introduce related libraries , Refer to official documentation . (3) In the project AppDelegate In general, there are three ...

  7. Integrate shareSDK WeChat 、QQ API Lead to cocoaPods Class not found symbol The solution to the problem

    because shareSDK Wechat and QQ API They only support 32 Bit , and cocoaPods The default is to support 64 Bit , So if you import these two into the project API There will be problems . I won't reprint the solution , The text is here : http://blog ...

  8. Android Integrate ShareSDK Share QQ Or space success , The reason why callbacks are not executed

    AndroidMainifest.xml As shown by the arrow in id Be sure to make contact with assets Next ShareSDK.xml Configured in QQ Of AppId It has to be the same . Here's the picture

  9. iOS:IOS Project integration ShareSDK Third party login 、 Share 、 Attention and other functions .

    Link to the original text :http://blog.csdn.net/daleiwang/article/details/34081231 (3) In the project AppDelegate In general, there are three operations , The first is to register Shar ...

Random recommendation

  1. wp8.1 Page back Page navigation

    public The_second() public second() { this.InitializeComponent(); Frame frame = Window.Current.Conte ...

  2. Servlet Development technology , establish , as well as Servlet Configuration of ,web.xml Configuration of

    Directly above , Don't bullshit !!! First of all : First, in the Eclipse In package Explorer , Single right mouse button , Select... From the shortcut menu that pops up “ newly build ”/Servlet command , Enter the new... In the pop-up dialog box Servlet The name of the package and class where it is located , And then click ...

  3. C Language resources

    0.C Bring your own library / Function online documentation http://www.acm.uiuc.edu/webmonkeys/book/c_guide/ 1.so Document making and use http://blog.csdn.net/love ...

  4. IntelliJ IDEA 14.0.2 Crack the registration code file (2015 year 06 month 08 Japan )

    Java File code : import java.math.BigInteger;import java.util.Date;import java.util.Random;import java.util ...

  5. logstash/conf.d Documentation

    logstash-01.conf input { beats { port => 5044 host => "0.0.0.0" type => "log ...

  6. Netty Series two ( transmission ).

    One . Preface In the last article we mentioned Netty The core component of  Channel. Callback .Future.ChannelHandler.EventLoop, This article is mainly about Channel (Netty Incoming and outgoing numbers ...

  7. Redis Common operations ----- character string

    1.APPEND key value If  key  Already exists and is a string , APPEND  The order will  value  Append to  key  The end of the original value . If  key  non-existent , APPEND  Simply give ...

  8. Compiler principle ( 6、 ... and ) Bottom up analysis LR analysis

    Bottom up analysis LR analysis explain : Take the teacher as an example PPT As the standard , Learn from some teaching materials ,AlvinZH Learning notes . Basic concepts 1. LR analysis : Scan from left to right (L) From the bottom up (R), It's the norm , That is, the rightmost derivation ( Normative derivation ) ...

  9. memcached Installation and startup

    windows install 1.4.4 edition https://pan.baidu.com/s/1xX1NThLqeq2zNMaqONFgkQ decompression ,“ As Administrator ” function cmd, Switch to memcached root directory , ...

  10. NetCore Use in Myrmec

    NetCore Use in Myrmec Myrmec What is it? ? Myrmec Is a library for detecting file formats ,Myrmec Different from other libraries or handwriting detection code ,Myrmec Does not rely on file extensions ( In practical use , Your users are likely to ...