I’ll be covering a very cool feature to add a new social feature in your game: posting in-game screenshots straight from the game to a Facebook album! I managed to do it today for a client game and it worked smoothly, so why not sharing?
What is covered in this article?
- Taking a screenshot via code from your Cocos2D game and storing it in an UIImage.
- Integrating Facebook into your Cocos2D game.
- Posting the screenshot to the Facebook account of the player (upon permission).
Taking Screenshots in Cocos 2D
This step was the easiest one for me. Oh wait, it’s not that easy to take a screenshot of the actual state of your game: what I have done was using a code written by Manu Corporat (Infinity Field developer). Grab the “Cocos2D Screenshot” methods here and add them inside the class CCDirectorIOS (cocos2d/Platforms/iOS/CCDirectorIOS.m) – it works for iPhone, iPhone 4 and iPad screenshots, e.g. all iOS devices and versions.
You can now take screenshots from your game by just calling:
UIImage *screenshot = [[CCDirector sharedDirector] screenshotUIImage];
You can even save this image in a folder (or even the Photo Album):
NSString *savePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Screenshot.png"]; // Write image to PNG [UIImagePNGRepresentation(tempImage) writeToFile:savePath atomically:YES];
Integrating Facebook into your Cocos2D game
- First of all, Setup a New App on Facebook: http://www.facebook.com/developers/. Once the application is created, click on the left tab “Mobile and Devices”, change the “Application type” to “Native App” and copy the “Application ID”.
- Open your Xcode project and add the following keys to your info.plist: Key: URL types -> Key: Item 0 -> Key: URL Schemes -> Key: Item 0 -> Value: fbYOUR_APP_ID (include the fb), it should look like:

- Clone the Facebook iOS-SDK from Git: https://github.com/facebook/facebook-ios-sdk.
– Drag the “src” folder into your Xcode project.
- If you want the official “Login with Facebook” blue button, open the folder “sample” that you cloned with the Facebook SDK, and right click “FBConnect.bundle” -> Show Package Contents -> copy and paste the images you want in your Cocos2D project. Consider renaming @2x to -hd.
- Import FBConnect.h into your Cocos2D Scene or Layer, the one in which you want to open the Facebook connection:
#import "FBConnect.h"
- Your class interface has to implement the Facebook delegates, as well have some members:
@interface HelloWorld : CCLayer
{
// Facebook
Facebook *facebook;
BOOL isFBLogged;
// GUI
CCLayer *shareLayer;
CCMenuItem *facebookLoginButton, *facebookLogoutButton;
CCLabelTTF *message;
}
- Add the GUI to handle facebook messages, as well the Login button (in this case you do as you wish, the way I’m doing is just an easy example). Although my GUI code is just an example, note that I’m inserting them inside a child CCLayer. When we are going to take the screenshot, we won’t want the Facebook button in the screenshot, nor the label saying “SHARE”, so I’ll just turn visibility of the layer on and off, instead of turning every element individually.
-(id) init
{
if( (self=[super init] )) {
CGSize size = [[CCDirector sharedDirector] winSize];
CCSprite *gameElement = [CCSprite spriteWithFile:@"poolplane.png"];
gameElement.position = ccp(size.width * .5, gameElement.contentSize.height * .5);
[self addChild:gameElement];
shareLayer = [CCLayer node];
[self addChild:shareLayer];
facebookLoginButton = [CCMenuItemImage itemFromNormalImage:@"LoginWithFacebookNormal.png" selectedImage:@"LoginWithFacebookPressed.png" disabledImage:@"LoginWithFacebookPressed.png" target:self selector:@selector(facebookLogin)];
CCMenu *fbMenu = [CCMenu menuWithItems:facebookLoginButton, facebookLogoutButton, nil];
fbMenu.position = ccp(size.width * .5, size.height * .5 + facebookLoginButton.contentSize.height * 3); [shareLayer addChild:fbMenu]; message = [CCLabelTTF labelWithString:@"Share in Facebook!" fontName:@"Marker Felt" fontSize:24]; message.position = ccp(size.width * .5, fbMenu.position.y + facebookLoginButton.contentSize.height); [shareLayer addChild:message]; } return self; }
Logging in into Facebook and getting permissions
We may enable the user to login into his Facebook account by simply calling the Facebook:authorize method passing in the permissions we want to get. We also may already hide unecessary items for the screenshot before calling the Facebook authorize method. You will know why later on.
- (void) facebookLogin
{
// The screenshot is going to be taken instantly after the login,
// so already hide GUI/unecessary stuff
shareLayer.visible = NO;
if (facebook == nil) {
facebook = [[Facebook alloc] initWithAppId:@"FACEBOOK-APP-ID"];
}
NSArray* permissions = [[NSArray arrayWithObjects:
@"publish_stream", @"offline_access", nil] retain];
[facebook authorize:permissions delegate:self];
}
Now we implement the delegate functions to handle the login request responses. They are very simple. The game will take the screenshot right after logging in (inside FBSessionsDelegate:fbDidLogin) and that is why we’ve hidden the GUI before logging in (the takeScreenshot screen is detailed below).
#pragma mark -
#pragma mark FBSessionDelegate
/**
* Called when the user has logged in successfully.
*/
- (void)fbDidLogin {
isFBLogged = YES;
[self takeScreenshot];
}
/**
* Called when the user canceled the authorization dialog.
*/
-(void)fbDidNotLogin:(BOOL)cancelled {
if (cancelled) {
[message setString:@"Login cancelled. No Login, No Share, No Game! :)"];
} else {
[message setString:@"Error. Please try again."];
}
shareLayer.visible = YES;
}
Taking the screenshot, uploading to Facebook and handling the responses
This is where the real magic happens: sending the screenshot to Facebook. It’s a very simple GRAPH API call to “me/photos” that sends the UIImage we make with the CCDirector:screenshotUIImage method.
According to the documentation this call uploads an image to the application’s album in the user account: “We automatically create an album for your application if it does not already exist. All photos from your application will be published to the same automatically created album.”
- (BOOL) takeScreenshot
{
UIImage *tempImage = [[CCDirector sharedDirector] screenshotUIImage];
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
tempImage,@"message",
nil];
[facebook requestWithGraphPath:@"me/photos"
andParams:params
andHttpMethod:@"POST"
andDelegate:self];
[message setString:@"Uploading screenshot. Please wait..."];
shareLayer.visible = YES;
return YES;
}
The last step is handling the responses: the upload may fail or be successful. For the first case we would need to alert the user about the error andshow the Facebook button again and enable a new upload, for the later we have to show a positive notification for the user. In both case we need to show the GUI layer again.
#pragma mark -
#pragma mark FBRequestDelegate
/**
* Called when a request returns and its response has been parsed into
* an object. The resulting object may be a dictionary, an array, a string,
* or a number, depending on the format of the API response. If you need access
* to the raw response, use:
*
* (void)request:(FBRequest *)request
* didReceiveResponse:(NSURLResponse *)response
*/
- (void)request:(FBRequest *)request didLoad:(id)result {
[message setString:@"Photo posted in the \"APP NAME\" album on your account!"];
shareLayer.visible = YES;
}
/**
* Called when an error prevents the Facebook API request from completing
* successfully.
*/
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
[message setString:@"Error. Please try again."];
shareLayer.visible = YES;
}
Example/Template project
I’ve packed everything in a Cocos2D Xcode project, ready to be used and compiled: just change your Facebook App’s ID and adapt in your project.
Download the example project here.
This post is part of iDevBlogADay, a group of indie iOS development blogs featuring two posts per day. You can keep up with iDevBlogADay through the web site, RSS feed, Twitter.





We are Alfred (programming & art) and Débora (ideas) and we are passionate about games. Karnak Games is our indie iPhone and iPad games development studio. 




