Mini Tutorial: How to add Facebook to your iOS Cocos2d game

So you want to add Facebook integration to your iOS Cocos2d game (allow players to upload screenshots, videos or post stuff to their wall, like how awesome your game is). First off, hop to the Facebook Developers website and check out the Mobile part, there should be a Getting Started page, this page:

Getting Started Mobile Apps

https://developers.facebook.com/docs/guides/mobile/

Follow the steps. Once you’re done with that, you pretty much already know how to post the the player’s Facebook wall.

Next question, how to upload a photo or a video. For videos, just check out a how-to blog post by Christine Abernathy. Link:

How-To: Use the Graph API to Upload a Video (iOS)

https://developers.facebook.com/blog/post/532/

Just follow that tutorial.

For photos, just replace the video code to:

UIImage *img = [UIImage imageWithContentsOfFile: @”img.jpg”];
   
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys: img, @”picture”, nil];
   
[delegate.facebook requestWithGraphPath:@”me/photos”
                                  andParams:params
                              andHttpMethod:@”POST”
                                andDelegate:self];

But, but, but the samples are not for a Cocos2d project.

For a Cocos2d project it’s more or less the same.

So your AppDelegate.h will look something like this:

#import <UIKit/UIKit.h>
#import “FBConnect.h”

@interface AppDelegate : NSObject <UIApplicationDelegate, FBSessionDelegate, FBRequestDelegate>
{    UIWindow *window;
   
    Facebook *facebook;
}

@property (nonatomic, retain) UIWindow *window;
@property (nonatomic, retain) Facebook *facebook;
@property (nonatomic, retain) NSString *appId;

@end

Just take note of the Facebook related stuff. I also added a NSString appId, which will store our app’s id.

Somewhere in AppDelegate.m applicationDidFinishLaunching (before you run your game scene):

facebook = [[Facebook alloc] initWithAppId: @”<APPID>”];
   
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@”FBAccessTokenKey”]
        && [defaults objectForKey:@”FBExpirationDateKey”])
{   facebook.accessToken = [defaults objectForKey:@”FBAccessTokenKey”];
        facebook.expirationDate = [defaults objectForKey:@”FBExpirationDateKey”];
}

And then as mentioned in the previous examples, add this to code as well:

– (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{   return ;
}

When I ran my app on my device I encountered this error:

sgx error: background gpu access not permitted

So I Googled and found this link:

http://dougdiego.com/2010/10/01/sgx-error-background-gpu-access-not-permitted/

And it said add these lines of codes to the AppDelegate code:

– (void)applicationDidEnterBackground:(UIApplication *)application
{   [[CCDirector sharedDirector] stopAnimation];
}

– (void)applicationWillEnterForeground:(UIApplication *)application
{   [[CCDirector sharedDirector] startAnimation];
}

– (void)applicationWillResignActive:(UIApplication *)application
{   [[CCDirector sharedDirector] pause];
}

– (void)applicationDidBecomeActive:(UIApplication *)application
{  [[CCDirector sharedDirector] resume];
}

Now in your game scene, or wherever in your game that needs some Facebook thingamajigie, like when the player clicks on an upload screenshot to Facebook button: (These codes are based on the upload video tutorial)

-(void) uploadToFacebookTapped: (id) sender

{  AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
    if (![delegate.facebook isSessionValid])
    {  
        NSArray* permissions =  [[NSArray arrayWithObjects:
                                  @”publish_stream”, @”user_photos”, nil] retain];
       
        [delegate.facebook authorize:permissions delegate: self];
    }   else
    {   [self uploadScreenshot];
    }

}

– (void)fbDidLogin
{   [self uploadScreenshot];
}

-(void)fbDidNotLogin:(BOOL)cancelled
{    NSLog(@”fbDidNotLogin”);
}

-(void) uploadScreenshot
{   AppDelegate *delegate = [[UIApplication sharedApplication] delegate];
   
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   
    NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent: @”screenshot.png”];
   
    UIImage *img = [UIImage imageWithContentsOfFile: path];
   
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   img, @”picture”,
                                   nil];
   
    [delegate.facebook requestWithGraphPath:@”me/photos”
                                  andParams:params
                              andHttpMethod:@”POST”
                                andDelegate:self];
}

So what happens is, if your player is not logged into Facebook and is using the Facebook function for your app for the first time (for that session), it will redirect the player to the Facebook app, or a web browser to allow the player to login and authorize your app. Once that is done, the fbLogin function will be called. And then uploadScreenshot.

And the call back code:

– (void)request:(FBRequest *)request didLoad:(id)result
{    if ([result isKindOfClass:[NSArray class]])
    {   result = [result objectAtIndex:0];
    }
   
    NSLog(@”Result of API call: %@”, result);
}

– (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{   NSLog(@”Failed with error: %@”, [error localizedDescription]);
}

After the screenshot has been upload, request didLoad will be called, if there is some kind of error along the way, request didFailWithError will be called.

And that’s it 🙂

Making that Talking App!

So you know Talking Tom, you know, the cat on the iPhone that you can tickle, hit, and repeats your voice in this squeaky voice? And his friends…

https://purplelilgirl.files.wordpress.com/2011/08/c387b-talkingbabyhippo.jpghttps://i1.wp.com/a3.phobos.apple.com/us/r1000/024/Purple/de/08/17/mzl.xigukdzg.320x480-75.jpghttps://i1.wp.com/getandroidstuff.com/wp-content/uploads/2010/09/Talking-Tom-Cat.jpghttps://i2.wp.com/images.gamebase.com.tw/gb_img/0/001/469/1469470.jpg

So I wrote a series of tutorials months ago about how to make your own Talking app.

Check out the tutorial series:

And a couple of people have asked me for the sample project. Particularly about how Dirac. Since my previous project was work related, I obviously can’t give them that, so I sat down today, and whipped up a really simple sample project, which you guys can just copy the Dirac setup off.

It includes all the stuff mentioned in the tutorials, such as how to record the player’s voice, how to monitor when the player is talking and when the player stopped talking, and how to process the recorded audio using Dirac and play it.

Here’s a screenie of the project:

No, it doesn’t have a fluffy animal, and when you test it out, you’d find out that it doesn’t even talk like a chipmunk. Whoever can guess why, gets a, I don’t know, virtual pat on the head? 

To make it sound like a chipmunk, just adjust the pitch (the value is from 0-2, 0 being like really low voice, and 2 being well, chipmunky).

Link to the project: 

http://www.mediafire.com/file/dofz0hofjrlkrg9/VoiceChangingBowtie.zip

I’m providing the project as is, oh, and I only got to test on my Macbook Pro, because i don’t actually own a iOS device. So please test it for me? 

For questions, comments, and answer to why there is a red bowtie, just tweet, email of Facebook me, info is on my sidebar.

While you guys are at it, why don’t you check out some new iOS and books?

EDIT:

According to ManiacDev:

You may also need to tweak the threshold parameter in HelloWorldLayer.mm to get the recording working properly due to differences between the simulator and different iOS devices.

Thanks for pointing it out 🙂

He also mentioned:

Overall a pretty cool and useful audio effect. While you might have interest in building a Talking Tom app there are many other uses for this – such as changing the tempo of a song, or the key to make it easier to play or speeding up boring instructional audios without making the speaker sound like a chipmunk.