Thursday, December 20, 2012

Having problem on creating .ipa file from Xcode's "Product -> Archive" or "Build & Archive" method ?

                 Creating an IPA is done in a simple way from your Xcode : Product -> Archive (previously Build & Archive). After the Archive operation completes, go to the Organizer, select your archive, select Share and in the "Select the content and options for sharing:" pane set Contents to "iOS App Store Package (.ipa) and Identity to iPhone Distribution (which should match your ad hoc/app store provisioning profile for the project).
It's a simple stuff to do but BANggggg... You might be in trouble if you have been using some other static library, third party library, other xcode project files in your project. You might have following issue that disables your .ipa file selection :
 “No Packager exists for the type of archive and This kind of archive cannot be signed."

Wednesday, December 19, 2012

Opening iOS Apps from Browser or any other source using URL Scheme in iOS Devices

In this section, i will be describing about how to open up an app in iOS device either from a Browser or from any other application present in iOS devices.

First thing you need to do is to register a URL scheme  in to device which is done in your app's info.plist file. URL Scheme will be your key to open up your app from browser or any other app. Here are the step by step procedure :
First open up your info.plist
Step 1. Right-Click and “Add Row”
screen-capture.png

Wednesday, October 3, 2012

"Pull Down To Refresh" integration for updating data in UITableViews

Hello Guyz , in this section we will be talking about "Pull Down To Refresh" integration for updating your data in UITableView. This kind of effect can be seen in  facebook app, where we  pull down the view and it refreshes/updates the facebook feeds. In the similar way, in this section i will write a bunch of codes that basically do is: when we pull down the UITableView, it will updates its datasource and reload the table section. Here, is the example screen that will help you to understand about this effect more wisely.
download and add this dropdown image to be used in project named updateArrow.png

Tuesday, October 2, 2012

Rate/Review apps in iTuneStore from inside iOS application

Hello Guyz, in this section i will describe you, how we can write a review or rate an app in iTuneStore from inside iOS Application by writing few lines of code. The example i am showing here will directly open up the iTuneStore review section of your app  in your device (to be noted is that the bunch of code i am writing here will only work on actual device.)

-(IBAction) rateAndReviewInItuneStore:(id)sender{
 NSString* url = [NSString stringWithFormat: @"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%@",AppID];
     [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url ]];

}
Here, AppID = your Apple ID in your iTuneStore , can be found inside your app  in iTuneStore and under "App Infromation" section of your app (9 digit numbers).

"Follow us on Twitter" button integration in iOS Application

Hello Guyz, In this section i will show you the two different way to integrate "Follow us on Twitter" button from inside our iOS App. If you are a twitter user then you probably got what i am talking about. "Follow us" button is very popular in web apps, by integrating it we can directly follow some people or organization depending on the twitter screen name we choose to follow and in this section i will show you how we can integrate it from inside our iOS apps.

Method 1: Without using any API
 Without plugging into native twitter app or  using any other API in code, we could simple open a URL to do the job of Following some one in twitter.
-(IBAction)FollowUsOnTwitter:(id)sender {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://twitter.com/intent/user?screen_name=%@",TwitterAccountName]]];
}
Note : TwitterAccountName = your twitter account name you wish to follow, and it will open to follow that account in the browser.

Method 2: Using Twitter Framework for iOS 5 and later
  To be noted here is that Twitter framework is available  only for  iOS 5 and later version.
- First of all , add "Twitter.framework" and "Accounts.framework" to your project.
- now include #import <Accounts/Accounts.h> and #import <Twitter/Twitter.h> to your .h file.

Thursday, September 20, 2012

Moving Images/Objects around the screen using Touch function in iOS app

Hi Guyz, in this section i will give you the idea of moving your objects(Image in our case) in the screen using Touch function. In previous blog, we talked about the drag and drop method, where we were dragging some object from one position and dropping it to  another one but in this section we are only going to reposition/move the object in the screen.So basically in this section, we will see how the multiple images moved using touch function. Lets get started !!!!

Create multiple (say 4 in our case) UIImageView in your viewcontroller and connect it to the IBOutlet and assign them with different images.
In your .h file ;
  @property(nonatomic,retain) IBOutlet UIImageView *imageView1;
  @property(nonatomic,retain) IBOutlet UIImageView *imageView2
  @property(nonatomic,retain) IBOutlet UIImageView *imageView3;  
  @property(nonatomic,retain) IBOutlet UIImageView *imageView4; 
In your .m file,
  @synthesize imageView1,imageView2,imageView3,imageView4;
Now,use Touch delegate method as :
  - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
       // get touch event
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self.view];
     if ([touch view] ==
imageView1) { // If touched view is imageView1 , then assign it its new location
               
imageView1.center = touchLocation;
    }
       else if ([touch view] ==
imageView2) {
          
imageView2.center = touchLocation;
    }
    else if ([touch view] ==
imageView3) {
              
imageView3.center = touchLocation;
    }
    else if ([touch view] ==
imageView4) {
              
imageView4.center = touchLocation;
    }
}

 So that's it!! so simple to move objects around the screen in iOS apps.


Tuesday, September 18, 2012

Draging and Droping objects in iOS App

Hi Guyz, in this section i will  describe you how to drag any particular views/objects and dropping it somewhere else. This is the nice feature  mostly seen in web apps, but here i will be detailing how to use this features in iOS Apps. In this demo, we will be changing the background color of UIView (where we will be dropping objects) depending on the dragged object's color and i will also give you a hint to change the position(repositioning it) of dragged object's as a result of Drag and Drop.
Lets get started !!!!

First design your  ViewController.xib file  as in figure with four dragging objects(here,UIImageView) and one UIView (as dropping target view). Change the background color of all 4 UIImageViews.
Now in .h file,
   // connect target UIView in Interface Builder
@property (nonatomic, strong) IBOutlet UIView *dropTargetView;
     // define temp UIImageView for view being dragged
@property (nonatomic, strong)  UIImageView *dragObjectView; 
    //distance between the actual touch point and the upper left corner of the dragObject
@property (nonatomic, assign) CGPoint touchOffset;
  // drag object's original position  in screen
@property (nonatomic, assign) CGPoint homePosition;

Monday, September 17, 2012

Creating PDF file from simple Texts/NSStrings/UIImages in iOS App

Hi Guyz, In this section i will write you a bunch of custom methods that can be used for generating PDF files from your simple texts and NSStrings in iOS app. In this section, we will be using core Graphics functions of Objective-C, No frameworks are used. You can have your own design customization  beside what i have designed here. I hope this blog will help you to start generating PDF as per your requirements. Lets start coding!!!

Lets define some variables and constants in .h file:
    #define kBorderInset            20.0
    #define kBorderWidth            1.0
    #define kMarginInset            12.0
    #define kLineWidth              1.0
    CGSize pageSize;

-(IBAction)generatePdfButtonPressed:(id)sender; //UIButton method for generating PDF
Now, in .m file : (lets have some custom methods)
- (void) drawBorder{
    /***get the current context, select a color for the border, specify a rect for the border, which has an inset of 20 pixels, and then just stroke the rect using normal Core Graphics.***/
    CGContextRef    currentContext = UIGraphicsGetCurrentContext();
    UIColor *borderColor = [UIColor brownColor];
    CGRect rectFrame = CGRectMake(kBorderInset, kBorderInset, pageSize.width-kBorderInset*2, pageSize.height-kBorderInset*2);
    CGContextSetStrokeColorWithColor(currentContext, borderColor.CGColor);
    CGContextSetLineWidth(currentContext, kBorderWidth);
    CGContextStrokeRect(currentContext, rectFrame);
}

Thursday, September 13, 2012

Bridging between JavaScript & Objective-C for Hybrid iOS Apps

Hi Guyz, in this section i will write about the bridging between the native Objective-C code with the web portion(JavaScript/HTML) code. The iOS hybrid application delivers a native experience on iOS devices by wrapping the mobile Web storefront with a native shell. The native shell elements are coded using the iOS Software Development Kit (SDK), while the storefront is accessed using the mobile Web interface. That generally means  hybrid app is a combination of web app + native iOS features. We use UIWebView for loading the webapp (linking URL) and we can have our own iOS feature included with it. So, In this section, i will be describing about how to call native Objective-C method from particular button in web portion and vice versa.

Call Javascript function from Objective-C

  // In your Javascript files:
    function myJavascriptFunction () {
        // Do whatever your want!
        }
       // -----------------------------------
       // And in your Objective-C code:
    // Call Javascript function from Objective-C:

    [webViewObject stringByEvaluatingJavaScriptFromString:@"myJavascriptFunction()"];

Call Objective-C function from Javascript

// In Objective-C
    - viewDidLoad {
        webView = [[UIWebView alloc] init];
        // Register the UIWebViewDelegate in order to shouldStartLoadWithRequest to be called (next function)
        webView.delegate = self; 
    }

Thursday, September 6, 2012

Creating Custom UIProgressView

Hi Guyz. In this section i will be creating a custom UIProgressView Class using DrawRect: method and two images (for background, and progress filling image). The images and screenshot of this section is here attached with. In the similar way you can have your own images to fit as per your requirement.
Standard iOS UIProgressView : 
Custom UIProgressView : 



Now, Lets create/add a New Objective -C Class in your project. Now, in your header file make it a subclass of UIProgressView.
@interface CustomProgressView : NSObject  --> @interface CustomProgressView : UIProgressView
your .h file : //  CustomProgressView.h
#import <UIKit/UIKit.h>
@interface CustomProgressView : UIProgressView
@end

Monday, September 3, 2012

Taking ScreenShot programmatically in Objective-C

Hi Guyz, in this section i will  show you a custom programmatic method for taking screenshot of any Views within your iOS application and storing it to Photo Library of your device. The custom method i am writing here simply returns UIImage of screen you are capturing, hence use this UIImage as per your requirements.
-(UIImage *) takeAScreenShot {
// here i am taking screen shot of whole UIWindow, but you can have the screenshot of any individual UIViews, Tableviews  . so in that case just use  object of your UIViews instead of  keyWindow.
       UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
     if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) // checking for Retina display   

         UIGraphicsBeginImageContextWithOptions(keyWindow.bounds.size, YES, [UIScreen mainScreen].scale);
       //if this method is not used for Retina device, image will be blurr.

}
    else
    {  UIGraphicsBeginImageContext(keyWindow.bounds.size);

}
    [
keyWindow.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

   // now storing captured image in Photo Library of device
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

/*** if you want to save captured image locally in your app's document directory
       NSData * data = UIImagePNGRepresentation(image);

NSString *imagePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"testImage.png"];
    NSLog(@"Path for Image : %@",imagePath);
    [data writeToFile:imagePath atomically:YES];

*******************************/
     return image;
 }

Note : Include #import <QuartzCore/QuartzCore.h>  for using CALayer property.

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];