Monday, August 27, 2012

Twitter integration on iOS 5 & later (Tweets only)

Hi folks,
  In this section we are going to explore new Apple framework "Twitter.framework" which is available from iOS 5. There are lots of things you can track with this framework like tweeting from your app, extracting profile and pictures of others from within your app etc. But, for this blog we are only going to send out tweets from our iOS apps. Along with the tweet text, i will even show you how to add image/pictures and links with the tweet. Lets get started then:

1. Add Twitter.framework and Accounts.framework to your project. One thing to be noted is if you are going to support your app for below iOS 5 too then you have to weak link the Twitter framework since it is not available for older versions. For this, simply click on the Twitter.Framework on the Build Phases of your target settings and change the "Required" drop down to "Optional".
2. Include #import <Twitter/Twitter.h> in your .h file.
3. Now, lets write a code for tweeting in a custom method :
-(IBAction)sendTweetsFromYourApp : (id) sender {
if(NSClassFromString(@"TWTweetComposeViewController")!= nil){  // this if call is required if you are going to support your app for older than iOS 5, this simply checks whether this Tweet class is available or not in running device (we do have to weak link Tweeter framework as described above for older iOS,But for app targeting iOS 5 and later this check is not required.)

Friday, August 24, 2012

E-Mail address validation in iOS app

Email validation custom method :

 -(BOOL) validEmailAddress:(NSString*) emailString {
    NSString *regExPattern = @"^[A-Z0-9._%+-]+@[A-Z0-9.-]+.[A-Z]{2,4}$";
    NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil];
    NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])];
    if (regExMatches == 0)
        return NO; // email invalid
     else
        return YES; // email valid
  }

Now, just call above method from where you want to validate email address (pass your email address as a emailString to this method).
For eg:
 if ([self validEmailAddress:yourEmailAddressText] == YES) {
      //email valid
}
else {
    //email invalid
}

Thursday, August 23, 2012

Pop-Up ViewController for iPad applications

In this section, i will guide you to show a pop up viewcontroller just like in attached picture for iPad application. To design a pop up viewcontroller, we are going to use Apple's UIPopoverController class and its delegates. You can use UIViewController or UITableViewController as per your requirement in popup view.

1. In your root .h class

    - Include <UIPopoverControllerDelegate>
    - @property(nonatomic,retain) UIPopoverController *popOverView;
    -(IBAction) showPopupViewController : (id) sender ;  // button method from where you want to show pop up

Different TextStyles in a single UILabel

In  general, i will say most of you guyz, will use two UILabels back to back to adjust the text/string of different styles like in colorwise,bold/nonbold etc. But here , i will show you another way to achieve this by simply using one UILabel to show text having different style.
For this section we will customize two different text in a single label,and keep in mind that in the similar way you can even customize more text in a single label.
Lets create a custom UILabel :
   UILabel *customLbl = [[UILabel alloc] initWithFrame:CGRectMake(50, 100, 200, 25)];
   customLbl.backgroundColor = [UIColor yellowColor];
    [self createTwoTextStyleInSingleUILabel:customLbl];// custom method calling
   [self.view addSubview:customLbl];
Now, lets create a custom method for customizing textstyles:
- (void)createTwoTextStyleInSingleUILabel: (UILabel *) myLabel;
Before applying this method,  add QuartzCore framework (needed for CALayers), and CoreText framework(needed for the attributed string.) 

Wednesday, August 22, 2012

Calculating Distance between two locations

In this section, i will show you the easy way of calculating distance between the any of two locations in meters or miles. First of all, we need to have the Longitude and Latitude of those locations to calculate their distance, and for getting latitude and longitude please have a look at MapKit framework and tutorials.
Here i assume we have the required longitude and latitude of those two locations.
For example:
Location 1 ->  double  long1 = -117.321570;   double  lat1 = 33.115120;
Location 2 ->  double  long2 = -122.406417;   double  lat2 = 37.785834;
Now, making CLLocation object for both locations;
CLLocation *location1 = [[CLLocation alloc] initWithLatitude: lat1 longitude:long1];
CLLocation *location2 = [[CLLocation alloc] initWithLatitude: lat2 longitude:long2]; 
NSLog(@"LOC1  = %f, %f", location1.coordinate.latitude,  location1.coordinate.longitude);
NSLog(@"LOC2 = %f, %f", location2.coordinate.latitude, location2.coordinate.longitude);
// now calculating the distance using inbuild method distanceFromLocation:
 float distInMeter = [location1 distanceFromLocation:location2]; // which returns in meters
//converting meters to mile
float distInMile = 0.000621371192 * distInMeter;
NSLog(@"Actual Distance in Mile : %f",distInMile);

Tuesday, August 21, 2012

Animating UINavigationBar

In this section, i will show you the code for hiding and showing UINavigationBar with smooth animation effect.
Lets say , your UINavigationBar object is  : UINavigationBar *navigationBar;

- (void) animateAndShowNavBar{
    // get the frame of navigation bar
    CGRect navBarFrame = navigationBar.frame;
    // set the beginning y coordinate of the title/navigation bar. Its 0(on the top) for this case
    navBarFrame.origin.y = 0;
 
// Now, to animate use one of the method below:
/* For iOS 4 and later we can use the following code to animate :
[UIView animateWithDuration:0.5 delay:0.0 options: UIViewAnimationCurveEaseOut   animations:^
     {
         navigationBar.frame = navBarFrame;
     }
       completion:^(BOOL finished)
     {
         NSLog(@"Done!");
     }
     ];
/* end of animation for iOS 4 and later ........*/

Monday, August 20, 2012

UI Element customization on iOS 5

From iOS 5, Apple has included many new APIs you can use to easily customize the appearance of various UIKit controls. We can use these features for each and every UI Elements as per requirement but moreover, iOS 5 has given us a new feature to customize our UI Elements once, that means we can customize the same UI Element all over the application by writing  code at once, and that part of customizing code is written in  application:didFinishLaunchingWithOptions: in application delegate class. If you are still confuse with my description then please have a look at the code written below, that will help you to understand what i am trying to describe.

Method: - resizableImageWithCapInsets:
   -Used to create resizable UIImages for iOS app, helps to stretch images. 
    - For the cap insets, you basically specify the fixed region of a given image in top, left, bottom, right. For example if you want whole image thing to be stretched then we pass 0 for all parameters :UIEdgeInsetsMake(0, 0, 0, 0). And lets say if you don't want to stretch 7 leftmost pixel and 5 rightmost pixel of UIImage(mainly the case for UIbutton images) , then we pass the parameters as :UIEdgeInsetsMake(0, 7, 0, 5).
    -  For using this property, you don't need to have large image, you should/may have small image with better resolution so that it can be stretchable without any problem.
 
1. Adding an Image as a UIColor  to the UIView 
     // This feature is available in older version too
    - (void)viewDidLoad {  
          [super viewDidLoad];
          [[self view] setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"your image name"]]];   
         }


2. Customizing UINavigationBar

Wednesday, August 15, 2012

Web Server connection from iOS Application

In this  section , i will be describing how to access and update the data from/to web server backend. General scenario for this section is that, iOS device has the front end GUI for data visualization and we gonna fetch the data from backend database which is simply web server  and we will format the reponse data using JSON Library.
At first, we need to download JSON Library from https://github.com/downloads/stig/json-framework/JSON%20v3.0beta2%20(iOS).zip  . Unzip it and drag the JSON "Classes" folder to your running project. Now import  #import "JSON.h" and  #import "SBJson.h"
There are two ways of accessing the data  from web server: HTTP Post and Get method. HTTP Post is more secure way so i will prefer you to use Post method.

HTTP POST Method and JSON Formatting

1. Preparing HTTP Post data :
      NSString *jsonRequest_PRE,*jsonRequest,*fixedURL;
    // prapare the parameter you want to send in server, here eg: username and password
      jsonRequest_PRE =    [NSString stringWithFormat:@"username=%@ password=%@",tempUserName,tempPassword];
      jsonRequest =    [jsonRequest_PRE    stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
      // Now, load your URL for server
        fixedURL = [@"Your Server Url" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
      // Now, praparing the complete HTTP request data
    NSURL *url = [NSURL URLWithString:fixedURL];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:1 timeoutInterval:30];
     NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
     [request setHTTPMethod:@"POST"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"close" forHTTPHeaderField:@"Connection"];
    [request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody: requestData]; // loading your parameter as a HTTP body

Tuesday, August 14, 2012

Working with Camera and Photo Library for iOS app

In this section, i will be describing you how to take a picture from camera inside your iOS app and how to store and select images from your iOS device photo library to the app of yours.
For this section we will be using UIImagePickerController class which needs UIImagePickerControllerDelegate and UINavigationControllerDelegate protocols to be defined.

1. Add MobileCoreServices framework to your project and add import
          #import <MobileCoreServices/MobileCoreServices.h>
2.Include <UIImagePickerControllerDelegate,UINavigationControllerDelegate> in .h file.
3. Lets declare some custom methods :
       - (void)takePictureFromCamera; // call it if you want to take a picture from camera
       - (void)usePictureFromCameraLibrary; // call it if you want to use picture from your device's photo library
Note : Best practice is to use UIActionSheet for displaying above two options so that user will have ease to choose pictures how they want.
  define bool variable:   BOOL newImage;  // its a flag to know which method is called
4. Now lets write custom method definition :

Monday, August 13, 2012

Sending E-mail from your iOS App

Hi Guys , In this section i will  describe you how to send an e-mail from your app. I don't think we need more explanation on this topic, as Apple has given us a simple framework <MessageUI> for doing this. You just need to know how to implement its class and delegates.
Below are the steps that will help you to send an email from your app :

1. Include MessageUI Framework to your project and import  #import "MessageUI/MessageUI.h"
2. Include  MessageUI delegate  <MFMailComposeViewControllerDelegate>       
3. Lets define some custom method in .h file for customizing the email composing view
    -(void)displayComposerSheet : (NSString*) address withSubject:(NSString*) subject withContent:(NSString*) content;
   - (void) email: (NSString*) address withSubject:(NSString*) subject withContent:(NSString*) content;
4. Now, lets make a call from where you want to display a  email composer sheet
     -(IBAction)emailMe { // This is the method from which you want to send email
[self email:@"jwarchansameer1@googlemail.com" withSubject:@"Message Header" withContent:@"your message goes here..."]; 
}

Friday, August 10, 2012

Reading and Downloading PDF in iOS App

In this blog, i will show you how to read PDF/docs file in your app and the way of downloading and saving PDF from its downloading links to apps documents directory. In the similar way , we can read docs file too.

First create UIWebView in your pdf display view, because we are going to use UIWebView to  display the pdf or docs file.
 Include <UIWebViewDelegate>
eg: IBOutLet UIWebView *yourWebView;

Section 1: Only Reading PDF/Docs file

/**************************************************************/

Note : Follow this section if you are reading your pre-stored files. If you are reading the pre-stored files like those in Resource folder , you don't need to go the next section.That means , in this section we assume that your pdf/docs file is already present in your project resource.
In your ViewDidLoad :
         NSString*  filePath= [[NSBundle mainBundle] pathForResource:@"sample" ofType:@"pdf"]];
        /// or you can even read docs file as : pathForResource:@"sample" ofType:@"docx"]
-->
         NSURL *url = [NSURL fileURLWithPath:filePath];
         NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
         [yourWebView setUserInteractionEnabled:YES];
         [yourWebView setDelegate:self];
         yourWebView.scalesPageToFit = YES;
         [yourWebView loadRequest:requestObj];
/**************************************************************/

Thursday, August 9, 2012

Scrolling UITableView (UITexField) withrespect to Keyboard

In the earlier post, I described about scrolling the UIView containing textfields  so that the keyboard will not hide textfields when it appears. Now, in this blog we gonna talk about the same case but with different scenario. This time i am assuming our uitextfied is inside the tableview cell and the following code ensures that those textfields will not hide behind the keyboard.
For this section , I am using NSNotificationCenter  to know whether keyboard is appearing or not , along with instead of scrolling the whole view  i am simply using the contentOffset property of tableview(UIScrollView).

1. Lets define custom method for registering the NSNotification
- (void)registerForKeyboardNotifications{
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:)
                      name:UIKeyboardDidShowNotification object:nil];
     [[NSNotificationCenter defaultCenter] addObserver:self    selector:@selector(keyboardWillBeHidden:)
                      name:UIKeyboardWillHideNotification object:nil];
  }

2. calling our custom registering nsnotification method when textfield is tapped
       (include textfield delegate in header file)
- (void)textFieldDidBeginEditing:(UITextField *)textField{
      [self registerForKeyboardNotifications];
}

Scrolling UIView (UITexField) withrespect to Keyboard

When your UITextFields are  below the middle of device height, it is obvious that the iPhone/iPad keyboard will hide them and we can not see what we are typing.
The following bunch of codes will ensure that the views will be scrolled up when keyboard appears and views will have its original position when keyboard dissapears.  The simple logic for this section is that, we simply play with the vertical origin (origin.y) of UIView and framing it up and down as respect to keyboard appearance.We do include animation effect as well so that the scrolling will look smooth.

1. Lets define some constants :
      static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
      static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
      static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
      static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;
      static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;

2. Include textfield delegate in your class <UITextFieldDelegate> and declare variable
            CGFloat animatedDistance;

Wednesday, August 8, 2012

Few tips on NSDate

Formatting Current NSDate

 NSDate *today = [NSDate date];
 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
   [formatter setDateFormat:@"MM/dd/yyyy"];
 NSString *fromDateString=[formatter stringFromDate:today];
   NSLog(@"Current Date  : %@",fromDateString); 

 Sorting array of NSDate

NSArray *timeArray = [NSArray arrayWithObjects:@"07/27/2012",@"08/29/2012",@"05/30/2012",@"04/01/2012",@"07/27/2013", @"07/27/2011",nil];
 NSMutableArray *testArray = [[NSMutableArray alloc]initWithObjects:nil, nil];
 

Alternative to iOS Device UUID

Since from iOS 5, Apple has deprecated the  UIDevice uniqueIdentifier , that means traditional way of getting the unique id of each iOS device won't work now  ie.
  [[UIDevice currentDevice] uniqueIdentifier]    fails from iOS 5 and more.


So for the alternative to the UUID , we can use the CFUUID class of Apple in order to create unique id for device. But, we really need to keep in mind that this inbuild class will create random numbers so they will return different ids on every call. Don't use NSUserDefaults for storing it, best way is to use Keychain.

So, here I am giving you the best way of using it in order to use it as a unique key for your device.

- (NSString *)createNewUUID {

    CFUUIDRef theUUID = CFUUIDCreate(NULL);
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    CFRelease(theUUID);
    return [(NSString *)string autorelease];
}

Handling NSDocumentDirectory of your app to store plist files

Normally, the plist files in Resource folder of iOS projects are readable only , that means those plist file can not be modified or we can not update it. So, to over come this problem , to set the read/write property to the plist we need to save/create them in the documents directory  of app.

Following code shows  how to  create plist file  in device's documents directory :

1. Creating plist file in Documents Directory
    1.1 Copying plist file from project resource folder to documents directory
   // this assumes you have plist file created manually in your project resource folder and here we are simply copying it from resource bundle to documents directory
  
   NSError *error;
// returning the path array of documents directory
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,   NSUserDomainMask, YES);   
//  returning the path at index 0
   NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"testFile.plist"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
// checking plist file already exists or not , if not then copy it from resource folder to documents directory
    if (![fileManager fileExistsAtPath: path]) 
    {
        NSString *bundle = [[NSBundle mainBundle]pathForResource:@"testFile" ofType:@"plist"];
        [fileManager copyItemAtPath:bundle toPath: path error:&error];
    }

Creating Dyanamic UITableViewCell Height

  Creating Dyanamic UITableViewCell Height

This sample code shows how we can create uitableviewcell height dynamically based on the text it consists.
Let assume we have UILabel in cell which contains some text, and code below  creates the appropriate cell in tableview depending on the label size :

1. Lets define some constants for the program:
      #define FONT_SIZE 14.0f
      #define CELL_CONTENT_WIDTH  305.0f
      #define CELL_CONTENT_MARGIN  8.0f

2. Return the height of each cell depending on its label size : 

    - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
        NSString *text =@"Read your text for each cell here (from Array or Dictionary)";
         // calculating the size of the text/string
        CGSize constraint = CGSizeMake(CELL_CONTENT_WIDTH - (CELL_CONTENT_MARGIN * 2), 20000.0f);
        CGSize size = [text sizeWithFont:[UIFont systemFontOfSize:FONT_SIZE] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];