Sunday, May 1, 2011

Twitter Connections and Post in iPhone SDK

Hello Friends,

Now we will start learning integration of twitter with our application. First you have to register your application with twitter, then they will give you Consumer Key and Consumer Secret. These both keys are necessary for twitter integration.


  • Download yajl library from the internet. Yajl
  • Add the following code to your project. I recommend you to use oAuth+MGTwitterEngine for the twitter integration. 
  • Insert following code for the header file to define constants.
#define kTwitterConsumerKey @"VcpHtgcXcLYFRAkZssZo9R"
#define kTwitterConsumerSecret @"JCHJtoQ5Ihjq7sxbvRkHLuAZBxZc4LEn66Fldcx5tXZ"
#define kCachedXAuthAccessTokenStringKey @"cachedXAuthAccessTokenKey"


  • Call this method on twitter button pressed event.
[self xAuthAccessTokenRequestButtonTouchUpInside];

  • Add the following methods to your class file. Following methods are twitter methods.
#pragma mark --------------Twitter Methods------------------
#pragma mark -
#pragma mark Actions

- (void)xAuthAccessTokenRequestButtonTouchUpInside
{
NSString *username = twitterUserName;// self.usernameTextField.text;
NSString *password = twitterPassword;//self.passwordTextField.text;

NSLog(@"About to request an xAuth token exchange for username: ]%@[ password: ]%@[.",
username, password);

[self.twitterEngine exchangeAccessTokenForUsername:username password:password];
}

- (void)sendTestTweetButtonTouchUpInside
{
NSString *tweetText = [NSString stringWithFormat:@"Welcome to your First Twitter Application"];
NSLog(@"About to send test tweet: \"%@\"", tweetText);
[self.twitterEngine sendUpdate:tweetText];
}

#pragma mark -
#pragma mark XAuthTwitterEngineDelegate methods

- (void) storeCachedTwitterXAuthAccessTokenString: (NSString *)tokenString forUsername:(NSString *)username
{
//
// Note: do not use NSUserDefaults to store this in a production environment. 
// ===== Use the keychain instead. Check out SFHFKeychainUtils if you want 
// an easy to use library. (http://github.com/ldandersen/scifihifi-iphone) 
//
NSLog(@"Access token string returned: %@", tokenString);

[[NSUserDefaults standardUserDefaults] setObject:tokenString forKey:kCachedXAuthAccessTokenStringKey];
UIAlertViewQuick(@"Authentication Success", @"Your username and password have successfully authenticated.", @"OK");
[[UIApplication sharedApplication] endIgnoringInteractionEvents];

// Enable the send tweet button.
//self.sendTweetButton.enabled = YES;
}

- (NSString *) cachedTwitterXAuthAccessTokenStringForUsername: (NSString *)username;
{
NSString *accessTokenString = [[NSUserDefaults standardUserDefaults] objectForKey:kCachedXAuthAccessTokenStringKey];

NSLog(@"About to return access token string: %@", accessTokenString);

return accessTokenString;
}


- (void) twitterXAuthConnectionDidFailWithError: (NSError *)error;
{
NSLog(@"Error: %@", error);

UIAlertViewQuick(@"Authentication error", @"Please check your username and password and try again.", @"OK");
[[UIApplication sharedApplication] endIgnoringInteractionEvents];
}


#pragma mark -
#pragma mark MGTwitterEngineDelegate methods

- (void)requestSucceeded:(NSString *)connectionIdentifier
{
NSLog(@"Twitter request succeeded: %@", connectionIdentifier);

UIAlertViewQuick(@"Tweet sent!", @"The tweet was successfully sent. Everything works!", @"OK");
}

- (void)requestFailed:(NSString *)connectionIdentifier withError:(NSError *)error
{
NSLog(@"Twitter request failed: %@ with error:%@", connectionIdentifier, error);

if ([[error domain] isEqualToString: @"HTTP"])
{
switch ([error code]) {

case 401:
{
// Unauthorized. The user's credentials failed to verify.
UIAlertViewQuick(@"Oops!", @"Your username and password could not be verified. Double check that you entered them correctly and try again.", @"OK"); 
break; 
}

case 502:
{
// Bad gateway: twitter is down or being upgraded.
UIAlertViewQuick(@"Fail whale!", @"Looks like Twitter is down or being updated. Please wait a few seconds and try again.", @"OK"); 
break; 
}

case 503:
{
// Service unavailable
UIAlertViewQuick(@"Hold your taps!", @"Looks like Twitter is overloaded. Please wait a few seconds and try again.", @"OK"); 
break; 
}

default:
{
NSString *errorMessage = [[NSString alloc] initWithFormat: @"%d %@", [error code], [error localizedDescription]];
UIAlertViewQuick(@"Twitter error!", errorMessage, @"OK"); 
[errorMessage release];
break; 
}
}

}
else 
{
switch ([error code]) {

case -1009:
{
UIAlertViewQuick(@"You're offline!", @"Sorry, it looks like you lost your Internet connection. Please reconnect and try again.", @"OK"); 
break; 
}

case -1200:
{
UIAlertViewQuick(@"Secure connection failed", @"I couldn't connect to Twitter. This is most likely a temporary issue, please try again.", @"OK"); 
break; 
}

default:
{ 
NSString *errorMessage = [[NSString alloc] initWithFormat:@"%@ xx %d: %@", [error domain], [error code], [error localizedDescription]];
UIAlertViewQuick(@"Network Error!", errorMessage , @"OK");
[errorMessage release];
}
}
}

}

  • You can download source code for the Twitter Integration from gitHub also. This contains sample application also. Download source code here.

No comments:

Post a Comment