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.

UIWebView Tutorial

Hello Friends,

Now we will use excellent feature of iOS SDK. In iOS apple has provided us ready made library for the web interaction. It is so finely designed that all the desired features are included in library. We can easily make browser application with this feature.

Now we will write a code to open www.apple.com website in application. We will start this work by creating View Based Application.

  • Create View Based Application and Give a name to it like WebView.
  • Open WebViewViewController.xib file in interface builder.
  • Drag a Web View from library to main View.
  • Now open WebViewController.h file and write a following code. 
@interface WebViewController : UIViewController {
IBOutlet UIWebView *webView;
}

@property (nonatomic, retain) UIWebView *webView;

@end
  • Now Save the header file and open interface builder again for connecting outlet again to the UIWebView which we have added just before to the main view.
  • After Connecting outlet to the UIWebView Controller, We can use that WebView in implementation file.
  • Do not forget to synthesize webView object in Implementation file. @synthesize method set the setter method for the webView object.
  • Now open WebViewController.m file and add the following code. 
- (void)viewDidLoad {
NSString *urlAddress = @”http://www.apple.com”;

//Create a URL object.
NSURL *url = [NSURL URLWithString:urlAddress];

//URL Requst Object
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

//Load the request in the UIWebView.
[webView loadRequest:requestObj];
}

  •  NSURL class is used to create an object which will hold the URL information.
  •  NSURLRequest is used to create a request to the URL.
  •  LoadRequest  method of UIWebView is used to load the request in the UIWebView.
Now Build and Run Program you should be able to see www.apple.com page. :-)

    Use of Image Picker in iPhone SDK


    Hello Friends now we will start to learn about image handling in iPhone. Apple has provided us most of the stuff ready for the use.  UIImagePicker is best example of that. We just have to invoke the function for the picking image from the iphone or to take image from camera.  Any novice developer can use this library easily.
    Methods of picking images from iPhone are deprecated. This method is available from iOS 3.0.
     Let’s start this stuff with View based Application.
    • Create View Based Application and Give a name to it.
    • Create IBOutlet and IBAction in ImageViewController.h. For that write following code  ImageViewController.h.
    @interface ImageViewController : UIViewController < UIImagePickerControllerDelegate,UINavigationControllerDelegate > 
    {
                   UIImageView *imageView;
                   UIButton *selectPhotobtn;
                   UIButton *takePhotobtn;
    }
    @property (nonatomic, retain) IBOutlet UIImageView *imageView;
    @property (nonatomic, retain) IBOutlet UIButton *selectPhotobtn;
    @property (nonatomic, retain) IBOutlet UIButton *takePhotobtn;
    
    -(IBAction) getPhoto:(id) sender;
    @end
    
    

            
    UIImagePickerControlDelegate and the UINavigationControllerDelegate are needed for properly interface with the image picker. 
    •  Create interface by opening ImageViewController.xib in the interface builder. 
    Ø  Drag a UIImageView on the main view.
    Ø  Set the Mode of the UIImageView to Aspect Fit in the Attribute inspector.
    Ø  Drag a UIButton on to the view and title it Select Photo.
    Ø  Drag another UIButton on to the view and title it Take Photo.

    • Connect the IBoutlets and IBAction

    Ø  Connect selectPhotobtn to the UIButton titled Select Photo.
    Ø  Connect takePhotobtn to the UIButton titled Take Photo.
    Ø  Connect the imageView to the UIImageView.
    Ø  Connect the Touch Up Inside Callback on each of the buttons to the getPhoto method.

    •   Now we have to implement the code for the getPhoto method.

    @synthesize imageView,selectPhotobtn,takePhotobtn;
     
    -(IBAction) getPhoto:(id) sender {
       UIImagePickerController * picker = [[UIImagePickerController alloc] init];
       picker.delegate = self;
     
       if((UIButton *) sender == selectPhotobtn) 
       {
               picker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
       } 
       else
       {
              picker.sourceType = UIImagePickerControllerSourceTypeCamera;
       }
      [self presentModalViewController:picker animated:YES];
    }
    

    
    
    • Once a photo is selected, the ImagePicker will callback to a method in our class called didFinishPickingMediaWithInfo.  This is a delegate method. Add the following code to ImageViewController.m file.

    - (void)imagePickerController:(UIImagePickerController *)picker 
    didFinishPickingMediaWithInfo:(NSDictionary *)info
    {
     [picker dismissModalViewControllerAnimated:YES];
     imageView.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    }
    

    
    
    In iOS everything is so finely designed that one can understand function use from its name. Only this stuff can create very good demo application in iPhone.