Facebook platform access in cocos2d-x

Source: Internet
Author: User
Tags browser cache

 

Introduction:

This document describes how to access the Facebook platform in the game to make the access process as detailed and simple as possible.

 Step 1: Authenticate)

One of the core classes in the Facebook SDK is fbsession, which is mainly used for user verification and management of user login processes.

Before writing code, you must first add the Facebook SDK. After downloading the SDK from the official website, add facebooksdk. Framework to the project so that we can use the Facebook interface.

Facebooksdk depends on two values in info. plist: facebookappid and URL types, as shown in:

 

After completing the above work, it is easy to request authentication. The Code is as follows:

void FacebookProxy::login(){    if (!FBSession.activeSession.isOpen) {        // if the session is closed, then we open it here        [FBSession.activeSession openWithCompletionHandler:^(                                                             FBSession *session,                                                             FBSessionState state,                                                             NSError *error) {            switch (state) {                case FBSessionStateClosedLoginFailed:                    //TODO handle here.                    m_isLogined = false;                    break;                default:                    m_isLogined = true;                    break;            }        }];    }}

Facebook's login code is asynchronous callback, and it is very convenient to process the callback using anonymous functions.

The logout code is as follows:

    if (m_isLogined){        [FBSession.activeSession closeAndClearTokenInformation];    }

It should be noted that after the player application authentication, because the browser (Safari) is used for login, The access_token will be left in the browser cache. To switch users, You need to exit the account in the browser, then log in.

 

Step 2: obtain user information

After passing step 1 authentication, you can call the Facebook interface. In this article, we mainly introduce the interface for getting user information and friend information.

The code for getting user information is as follows:

void FacebookProxy::loadUserInfo(PlatformUserInfo & info){    [[FBRequest requestForMe] startWithCompletionHandler:     ^(FBRequestConnection *connection,       NSDictionary<FBGraphUser> *user,       NSError *error) {         if (!error) {             //TODO                      }     }];}

The startwithcompletionhandler function is similar to the openwithcompletionhandler function. The callback function parameter user contains all user information (including user ID and user name ).

 

Step 3: Get friend information

The Code is as follows:

void FacebookProxy::loadFriends(std::vector<PlatformUserInfo*> & friends){    FBRequest* friendsRequest = [FBRequest requestForMyFriends];    [friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,                                                  NSDictionary* result,                                                  NSError *error) {        NSArray* friends = [result objectForKey:@"data"];        NSLog(@"Found: %i friends", friends.count);        for (NSDictionary<FBGraphUser>* friend_ in friends) {            NSLog(@"I have a friend named %@ with id %@", friend_.name, friend_.id);        }    }];}

Step 4: Share

The sharing function is one of the most important functions and has to be written. However, there is nothing special to note. The Code is as follows:

void _share(const char * name,const char * caption, const char * desc, const char * link, const char * picture){    NSMutableDictionary * postParams =    [[NSMutableDictionary alloc] initWithObjectsAndKeys:     [NSString stringWithUTF8String:link], @"link",     [NSString stringWithUTF8String:picture], @"picture",     [NSString stringWithUTF8String:name], @"name",     [NSString stringWithUTF8String:caption], @"caption",     [NSString stringWithUTF8String:desc], @"description",     nil];        [FBRequestConnection     startWithGraphPath:@"me/feed"     parameters:postParams     HTTPMethod:@"POST"     completionHandler:^(FBRequestConnection *connection,                         id result,                         NSError *error) {         NSString *alertText;         if (error) {             alertText = [NSString stringWithFormat:                          @"error: domain = %@, code = %d",                          error.domain, error.code];         } else {             alertText = [NSString stringWithFormat:                          @"Posted action, id: %@",                          [result objectForKey:@"id"]];         }         // Show the result in an alert         [[[UIAlertView alloc] initWithTitle:@"Result"                                     message:alertText                                    delegate:nil                           cancelButtonTitle:@"OK!"                           otherButtonTitles:nil]          show];     }];}void FacebookProxy::share(const char * name,const char * caption, const char * desc, const char * link, const char * picture){    if ([FBSession.activeSession.permissions         indexOfObject:@"publish_actions"] == NSNotFound) {        //No permissions found in session, ask for it        [FBSession.activeSession         reauthorizeWithPublishPermissions:         [NSArray arrayWithObject:@"publish_actions"]         defaultAudience:FBSessionDefaultAudienceFriends         completionHandler:^(FBSession *session, NSError *error) {             if (!error) {                 // If permissions granted, publish the story                 _share(name, caption, desc, link, picture);             }         }];    } else {        // If permissions present, publish the story        _share(name, caption, desc, link, picture);    }}
Conclusion

The several interfaces provided in this Article can basically meet general requirements, and the code is for reference only.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.