Integrating Twitter and Cocos2d (oAuth)

Yesterday I thought I’d try integrating posting to twitter from my cocos2d project. This took a long, long time so I thought a few other might benefit from my experience.

Before I begin, I just want to say thanks to everyone who contributed information to the posts and sites below. It would have taken me a long time without them!

A Warning

I’ve spend no time optimising this code or testing it. All the information below is what I’ve written from memory shortly after getting everything to work. I may have forgotten some details (but hopefully not!) and I’ve written this as a set of practical steps rather than a proper, explanatory tutorial. If there is demand, I may flesh this out a little more.

Get the Files

Firstly, go to the top link and grab the code. Then go to the final link and grab the downloads from there too.

Now open your project AND the project you grabbed from the first link. Drag the Twitter+OAuth group and all it’s files into to your project.

Now open the project you gabbed from the last link and copy the two xib files to your project. Also copy the Tweet.m & .h files as well as the iCodeOauthViewController.m & .h files (a total of 6 files).

Setup Your Project

In order to get your project to compile you’ll need to first include the libxml2 Framework (right click on your project and choose Add Exisiting Frameworks).

Now right click on your project and choose ‘Get Info’. In the build tab, scroll down till you see the ‘Search Paths’ section. In the ‘Header Search Paths’ field, add ‘$(SDKROOT)/usr/include/libxml2′

Finally, expand the Twitter+OAuth group in your project and then expand theMGTwitterEngine group. Open MGTwitterEngine.m and alter #define USE_LBXML 0 to #define USE_LIBXML 1.

Change your AppDelegate

Go to your appdeligate.m file and add

#import "SA_OAuthTwitterEngine.h"
#import "iCodeOauthViewController.h"

Find the applicationDidFinishLaunching method and add the following just before [window makeKeyAndVisible]

window.rootViewController = viewController;

Now add the following before your dealloc method

- (void)twitterAccountLogin
{
iCodeOauthViewController *twitterViewController = [[iCodeOauthViewController alloc] initWithNibName:@"iCodeOauthViewController" bundle:[NSBundle mainBundle]];
[viewController presentModalViewController:twitterViewController animated:YES];
}
//=============================================================================================================================
#pragma mark SA_OAuthTwitterEngineDelegate
- (void) storeCachedTwitterOAuthData: (NSString *) data forUsername: (NSString *) username {
NSUserDefaults			*defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: data forKey: @"authData"];
[defaults synchronize];

}

- (NSString *) cachedTwitterOAuthDataForUsername: (NSString *) username {

return [[NSUserDefaults standardUserDefaults] objectForKey: @"authData"];

}

//=============================================================================================================================

#pragma mark SA_OAuthTwitterControllerDelegate

- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {

NSLog(@"Authenicated for %@", username);

}

- (void) OAuthTwitterControllerFailed: (SA_OAuthTwitterController *) controller {

NSLog(@"Authentication Failed!");

}

- (void) OAuthTwitterControllerCanceled: (SA_OAuthTwitterController *) controller {

NSLog(@"Authentication Canceled.");

}

//=============================================================================================================================

#pragma mark TwitterEngineDelegate

- (void) requestSucceeded: (NSString *) requestIdentifier {

NSLog(@"Request %@ succeeded", requestIdentifier);

}

- (void) requestFailed: (NSString *) requestIdentifier withError: (NSError *) error {

NSLog(@"Request %@ failed with error: %@", requestIdentifier, error);

}

Finally, add the following to your dealloc method

[_engine release];

Now move on to your AppDelegate.h file. Add alter it to something like the below

#import
#import "iCodeOauthViewController.h"
#import "SA_OAuthTwitterEngine.h"
#import "SA_OAuthTwitterController.h"

@class RootViewController;
@class SA_OAuthTwitterEngine;

@interface GunMachineAppDelegate : NSObject  {
	UIWindow			*window;
	RootViewController	*viewController;
	SA_OAuthTwitterEngine *_engine;
}

@property (nonatomic, retain) UIWindow *window;
-(void) twitterAccountLogin;

@end

Are You Still With Me?

Open the iCodeOauthViewController.m file and add these:

#define kOAuthConsumerKey @"xxxxxx" //REPLACE ME
#define kOAuthConsumerSecret @"xxxxxxxxx" //REPLACE ME

You may also need to go back to your MGTwitterEngine.m file and remove the above lines from there.

You’ll also need to get your own key and secret from Twitter for your own app. You can sign up for this here: http://twitter.com/login?redirect_after_login=%2Foauth_clients.

Making it work

We’re almost there! All you need to do now is to define a menu item somewhere in your app which will allow you to post. I used the following code:

-(void) twitterTouched: (id) sender {

	[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"postToTwitter"];

	[[NSUserDefaults standardUserDefaults] synchronize];

	MyAppDelegate *myApp = (MyAppDelegate *)[UIApplication sharedApplication].delegate;
	[myApp twitterAccountLogin];

}

And called this with:

CCMenuItemFont* twitterItem = [CCMenuItemFont itemFromString:@"Twitter" target:self selector:@selector(twitterTouched:)];

We’ve Made It

So there you have it. My, probably far too brief, guide to implementing Twitter and Cocos2d.

Comments

  1. What’s the significant difference among the actual iphone 4 and iphone 5 that are coming out for US.?
    i want to fnd out should it be worth it to order the actual iphone 4 or if i should just wait for i phone five.

  2. Yenaphe says:

    Thanks for sharing such info. I’ve followed you exemple, but I’m getting 15 warnings:

    7 suggest parentheses around assignment used as truth value
    (mostly from stuff like if (self = [super init]) )

    4 MGT*Parser may not respond to ‘-parser:didEndElement:namespaceURI:qualifiedName:’

    and several others.

    Would you mind helping me resolve some of these warnings ?

  3. admin says:

    @Yenaphe – I get a few of those warnings too (haven’t had time to properly go through them yet) but they shouldn’t be causing any problems. These are issues with the downloaded code and Im guessing their just a result of not using best practice although probably not causing a real problem.

    Is your app crashing?

  4. Yenaphe says:

    @Phil: nope, the app is not crashing, but I try to remove all warning to lower the chance of bugs because I’m learning Obj-C and OOP.

    I’m left with one worning, do you know how I could remove it, I’m not sure to understand it sadly:

    iCodeOauthViewController.m:83: warning: local declaration of ‘tableView’ hides instance variable

Trackbacks

  1. [...] Projects « Integrating Twitter and Cocos2d (oAuth) [...]