Friday, November 30, 2012

How to store values in keychain of ios

How to store values in keychain of ios

Get contacts of all your emergency needs on single tap. Download Quick-Finder for iPhone

Tutorial for: Key chain, user defaults, values, KeychainItemWrapper, iphone, ios

What is keyChain -

Key chain is the place where we can store the values which will be retain even after deleting application. Generally we store username and password in it.


Difference between KeyChain and userDefaults
The values which are store in userDeafults are deleted when we delete the app from our device but the values stored in KeyChain will not.


Apple provides helper classes, for that you can refer to this link
htps://developer.apple.com/library/ios/#samplecode/GenericKeychain/Introduction/Intro.html#//apple_ref/doc/uid/DTS40007797
Or you can download it from here

Initialise the class

KeychainItemWrapper *wrapper = [[KeychainItemWrapper alloc] initWithIdentifier:@"Your application name" accessGroup:nil];

How to save the values
[wrapper setObject:@"PASSWORD" forKey:@"KEYPASS"];
[wrapper setObject:@"USERNAME" forKey:@"KEYUSER"];


how to retrive the values

NSString *pwd = [wrapper objectForKey:@"KEYPASS"];
NSString *user = [wrapperobjectForKey:@"KEYUSER"];


How to delete the values

[wrapper resetKeychainItem];

Reference: http://stackoverflow.com/questions/6972092/ios-how-to-store-username-password-within-an-app
www.Hypersmash.com

Thursday, November 29, 2012

How to implement hot search on tableView in iPhone

Keyword: Search bar, table view, iphone, ios, hot search, instant search, delegate, datasource, implement,



Get contacts of all your emergency needs on single tap. Download Quick-Finder for iPhone

       How to implement hot search on tableView in iPhone


You can download the source code from here


1)   Take a new project named TableSearch

2)  Add Table in viewController.xib named tbl;

3) Add a search bar named searchBar

4) Set UITableViewDataSource,UITableViewDelegate and UISearchBarDelegate to support Delegate methods.

4) Modify the code of ViewController.h (Modified code is in different color - brown )

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate,UITextFieldDelegate>
{
    NSMutableArray *tableArray; // stores all data 
    NSMutableArray *filterArray; // stores only searched data 
    NSMutableArray *displayArray; // shows data on table
}
@property (retain, nonatomic) IBOutlet UISearchBar *serchBar;
@property (retain, nonatomic) IBOutlet UITableView *tbl;

@end


4)Now modify the code of ViewController.m (Modified code is in different color - brown )



import "ViewController.h"

@implementation ViewController
@synthesize serchBar;
@synthesize tbl;
//
//
// Method to filter the data from total array with key, this method returns filtered array
//
//
-(NSMutableArray *)managingDisplayArrayFromArray:(NSMutableArray *)totalArray withKey:(NSString *)key
{
    NSMutableArray *ary=[[NSMutableArray alloc]init];
    key=[key lowercaseString];
    for (NSString *str in totalArray)
    {
      NSRange range = [str rangeOfString:key];
         if (range.location != NSNotFound )
             [ary addObject:str];
    
    }
    return ary;
}


// Implementation of textFiled delegate method
// This method will call on every type on text field of serach bar


-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSString *keyString=[textField.text stringByAppendingString:string];
    displayArray=[self managingDisplayArrayFromArray:tableArray withKey:keyString];
    [self.tbl reloadData];
    return YES;
}


// Implementation of searchBar delegate method
// This method will call on search button click

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    displayArray=[self managingDisplayArrayFromArray:tableArray withKey:serchBar.text];
    [self.tbl reloadData];
    [self.serchBar resignFirstResponder];

}

// Implementation of searchBar delegate method
// This method will call on cancle button click

-(void)searchBarCancelButtonClicked:(UISearchBar *) searchBar
{
    displayArray=tableArray;
    [self.tbl reloadData];
    [self.serchBar resignFirstResponder];

}
#pragma mark -- Implementation of table view delegate methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [displayArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    [cell.textLabel setText:[displayArray objectAtIndex:indexPath.row]];
    return cell;
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Initializing the arrays
    
    tableArray=[[NSMutableArray alloc]init];
    displayArray=[[NSMutableArray alloc]init];
    [tableArray addObject:@"ram"];
    [tableArray addObject:@"shyam"];
    [tableArray addObject:@"suresh"];
    [tableArray addObject:@"girjesh"];
    [tableArray addObject:@"sudhir"];
    [tableArray addObject:@"aknsha"];
    [tableArray addObject:@"vineeta"];
    [tableArray addObject:@"rakesh"];
    [tableArray addObject:@"himanshu"];
    [tableArray addObject:@"barkha"];
    displayArray=[NSMutableArray arrayWithArray:tableArray];
    self.serchBar.showsCancelButton=YES;
    
  // Following 3 line of code is written to support text field of searchBar and also here we are setting  delegate of that text filed
    
    
    NSArray *subViewsArray=[self.serchBar subviews]; 
    UITextField *txtField=(UITextField *)[subViewsArray objectAtIndex:1];
    txtField.delegate=self;

// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [serchBar release];
    [tbl release];
    [super dealloc];
}
@end


You can also download the code from here

Link for Source code http://adf.ly/FRVuX




Tuesday, November 27, 2012

How To Use shouldAutoRotate With Tab Bar controller in iOS6

Keyword: ios6, tab bar controller, delegate, rotation, category,should Autoraotate, interface orientatio


 Get contacts of all your emergency needs on single tap. Download Quick-Finder for iPhone

How To Use shouldAutoRotate With Tab Bar controller in iOS6



To Support tabBarController auto Rotation in iOS6. You need to make category for that.


Add new file in you project named UITabBarController+autoRotate. File should be subclass of NSObject.




Modified the code of  UITabBarController+autoRotate.h as 




#import <UIKit/UIKit.h>

@interface UITabBarController (autoRotate)<UITabBarControllerDelegate>

-(BOOL)shouldAutorotate;
- (NSUInteger)supportedInterfaceOrientations;

@end


And Modified the code of  UITabBarController+autoRotate.m as 






#import "UITabBarController+autoRotate.h"
#import "AppDelegate.h"// 


@implementation UITabBarController (autoRotate)

-(BOOL)shouldAutorotate {
    
    AppDelegate *delegate= (AppDelegate*)[[UIApplication sharedApplication]delegate];
    return [delegate.tabBarController.selectedViewController shouldAutorotate];
}


- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskAll;
}

@end

Thats it.

Note: you may have to change name of AppDelegate With your Project AppDelegate name.

Feel free to use comment section



Friday, November 23, 2012

How to show table having alphabetical ordered section

Keyword: ios6, table view, delegate,datasource, rotation, category,should Autoraotate, interface orientation, dictionary, section, cell, reuse identifier, iphone,sample project 

Get contacts of all your emergency needs on single tap. Download Quick-Finder for iPhone

How to show table having alphabetical ordered section


1) Create a new project name TableSample.

2) Open ViewController.xib and paste a tableView on it . Make the IBOutlet of it as 

     @property (retain, nonatomic) IBOutlet UITableView *tbl;

and also synthesize it.

3) Now Attach datasource and delegate of tableView with File owner.

4) Now open ViewController.h as (Modified code is in different color) 


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>

@property (retain, nonatomic) IBOutlet UITableView *tbl;
@property (nonatomic,retain) NSMutableDictionary *tblDictionary;
@property (nonatomic,retain)NSMutableArray *keyArray;
@property (nonatomic,retain)NSMutableArray *tableArray;
@property (nonatomic,retain)NSMutableArray *filteredArray;
@end






5) Now open ViewController.m

  implement the following method

  i) - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section

   // This method is used to create headers of section

 ii)   -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView


// This method is used to define number of sections

iii)- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

// This method is used for number of rows in each section


we are using a custom method that fill the values of array in dictionary.



6) Now Modified The code of ViewController.m as




#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize tableArray;
@synthesize filteredArray;
@synthesize tblDictionary;
@synthesize keyArray;


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *header=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 20)];
    [header setBackgroundColor:[UIColor blackColor]];
    UILabel *lbl=[[UILabel alloc]initWithFrame:CGRectMake(20, 0, 320, 20)];
    [header addSubview:lbl];
    [lbl setTextColor:[UIColor whiteColor]];
    [lbl setBackgroundColor:[UIColor clearColor]];
    [lbl setText:[keyArray objectAtIndex:section]];
    return header;


}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return  [keyArray count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    NSArray *ary=[self.tblDictionary valueForKey:[keyArray objectAtIndex:section]];
    return [ary count];

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"Cell"];
    NSString *key=[keyArray objectAtIndex:[indexPath section]];
    NSArray *array=(NSArray *)[self.tblDictionary valueForKey:key];
    NSString *cellTitle=[array objectAtIndex:[indexPath row]];
    [cell.textLabel setText:cellTitle];
    return cell;
}

-(NSMutableDictionary *)fillingDictionary:(NSMutableArray *)ary
{

// This method has the real magic of this sample

    keyArray=[[NSMutableArray alloc]init];
    [keyArray removeAllObjects];
    
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    
    // First sort the array
    
    [ary sortUsingSelector:@selector(compare:)];
    
    
    // Get the first character of your string which will be your key
    
    for(NSString *str in ary)
    {
        char charval=[str characterAtIndex:0];
        NSString *charStr=[NSString stringWithUTF8String:&charval];
        if(![keyArray containsObject:charStr])
        {
            NSMutableArray *charArray=[[NSMutableArray alloc]init];
            [charArray addObject:str];
            [keyArray addObject:charStr];
            [dic setValue:charArray forKey:charStr];
        }
        else
        {
            NSMutableArray *prevArray=(NSMutableArray *)[dic valueForKey:charStr];
            [prevArray addObject:str];
            [dic setValue:prevArray forKey:charStr];
        
        }
    
    }
    return dic;

}

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSMutableArray *ary=[[NSMutableArray alloc]init];
    [ary addObject:@"gfwfhlr"];
    [ary addObject:@"irofhqrlo"];
    [ary addObject:@"gfwtgfhlr"];
    [ary addObject:@"gegirofgewghqrlo"];
    [ary addObject:@"dsfgverg"];
    [ary addObject:@"gergqrlo"];
    [ary addObject:@"gregerg"];
    [ary addObject:@"gegqrlo"];
    [ary addObject:@"getwgtgt"];
    [ary addObject:@"uyuqrlo"];
    [ary addObject:@"hmnjmj"];
    [ary addObject:@"mjhmghqrlo"];
    [ary addObject:@"mjmjm"];
    [ary addObject:@"irofhmjmjqrlo"];
    [ary addObject:@"sgfwfhlr"];
    [ary addObject:@"daimrofh;qrlo"];
    [ary addObject:@"fgfwfhlr"];
    [ary addObject:@"girofhqrlo"];
    [ary addObject:@"hgfwfhlr"];
    [ary addObject:@"jirofhqrlo"];
    [ary addObject:@"kgfwfhlr"];
    [ary addObject:@"lirofhqrlo"];
    
    self.tblDictionary =[self fillingDictionary:ary];
    [self.tbl reloadData];
    
  // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [_tbl release];
    [super dealloc];
}
@end

You can also download the code from here

or click to link http://adf.ly/FBhKI







Thursday, November 22, 2012

How to show user current city name

Keyword: ios6, Core Location frame work, iphone,sample project, CLLocationManagerDelegate, CLLocationManager, startUpdatingLocation, setDesiredAccuracy,map

Get contacts of all your emergency needs on single tap. Download Quick-Finder for iPhone


How to show user current city name



1) Create a new Project with name of CityFinder and 
2) add FrameWork CoreLocation.FrameWork


3) Update the code of AppDelegate.h as follows ( Modified code is in different color - yellow )


#import <UIKit/UIKit.h>
#import <CoreLocation/CoreLocation.h>

@class ViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate,CLLocationManagerDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ViewController *viewController;
@property (nonatomic,retain) CLLocationManager *manager;
@property float latitude;
@property float longitude;




4) Synthesize all variables

@synthesize manager;
@synthesize latitude;
@synthesize longitude;








5) Update the code of method didFinishLaunching in AppDelegate.m as follows

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]   autorelease];
    self.window.rootViewController = self.viewController;
    
    self.manager=[[CLLocationManager alloc]init];
    [self.manager setDistanceFilter:CLLocationDistanceMax];
    [self.manager setDelegate:self];
    [self.manager setDesiredAccuracy:kCLLocationAccuracyBest];
    [self.manager startUpdatingLocation];
    [self.window makeKeyAndVisible];

    return YES;
}




6) Update xib of ViewController

   i) add a text view named txtView;
  ii) add an button and also an IBAction with it named  - (IBAction)clickToGetLocation:(id)sender


7) update the code of ViewController.h
   

    #import <UIKit/UIKit.h>

    @interface ViewController : UIViewController

    @property (retain, nonatomic) IBOutlet UITextView *txtView;
    - (IBAction)clickToGetLocation:(id)sender;
   @end

  

8) Code of click action 


- (IBAction)clickToGetLocation:(id)sender {
    
    AppDelegate *delegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
    
    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%f,%f&output=csv",delegate.latitude, delegate.longitude];
    NSError* error;
    NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
    locationString = [locationString stringByReplacingOccurrencesOfString:@"\"" withString:@""];
    self.txtView.text=[locationString substringFromIndex:6];
}






Now thats it 

Click on button. You will get current location on text View.



Note:   If you are running this code on simulator you will get address  "1 stockton st,francisco, ca 94108 usa"  default location of simulator . You need to run this code on real device to get the current location.




You can also download the sample code from here


  http://adf.ly/F9ECK


If you have any question, please put it in comment section.



How To Add Events To Calendar in iOS 6

Key word:   EKEventStore, EventKit Framework, iCal, user permissions, requestAccessToEntityType, Privacy settings, ios6

Get contacts of all your emergency needs on single tap. Download Quick-Finder for iPhone

How To Add Events To Calendar in iOS 6

Get contacts of all your emergency needs on single tap. Download Quick-Finder for iPhone

1) Now Apple make it compulsory to take user permission to add a event to iCal (As we are taking permission for location). So the code which you have written till yet will not work on iOS6.

For iOS 6, You need to take permission from user. For this you have to execute the following code.


 EKEventStore *eventstore = [[EKEventStore alloc] init];
 if([eventstore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) 

[eventstore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) 


if(granted)
{
// if user granted your app to use calendar control will reach over hare
// add the code to add event to iCal that you are using previously for iOS5

    EKEvent *event  = [EKEvent eventWithEventStore: eventstore];
    event.title     = [NSString stringWithStdString:eventName] ;
    event.startDate = [NSDate date];
    [event setCalendar:[eventStore defaultCalendarForNewEvents]];
    NSError *err;
    [eventStore saveEvent:event span:EKSpanThisEvent error:&err];

}
else
{
// if user did not your app to use calendar control will reach over hare
}

}];
}


If user did not allow your app to use calendar you can also suggest him to allow and shows alert massage like this

UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Info" message:@"Pls go to Setting----> Privacy -----> Calendar ----> Choose App Name. " delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];

[alert show];



Sunday, November 4, 2012

How to use should autorotate(ios 6) with navigation controller

Keyword: ios6, navigation controller, delegate, rotation, category,should Autoraotate, interface orientation

Get contacts of all your emergency needs on single tap. Download Quick-Finder for iPhone

How to use should autorotate(ios 6) with navigation controller

1)Take a project named AutoRotationSample
- project should be of empty application
- uncheck storyboard option.
- follow the below image.















                                                                       
  2) Now add new file of Subclass of UINavigationController






3) Now add two more view controllers named firstViewController and secondViewController
4) open AppDelegate.h and modify the code as follow (modified code is in different color)



#import <UIKit/UIKit.h>
#import "firstViewController.h"

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (nonatomic,retain) UINavigationController *customNavigation;
@property (nonatomic,retain)firstViewController *first;

@end


5) Open AppDelegate.m and import two files as

    #import "firstViewController.h"
    #import "CustomNavigationController.h"

and synthesize two variables as 

   @synthesize first;
   @synthesize customNavigation;

6) Now modify didFinishLaunchingMethod  as (modified code is in different color)


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    self.first = [[[firstViewController alloc] initWithNibName:@"firstViewController" bundle:nil]   autorelease];
    self.customNavigation=[[CustomNavigationController alloc ]initWithRootViewController:self.first];
    self.window.rootViewController = self.customNavigation;
    [self.window makeKeyAndVisible];
    return YES;
}



7) Now open CustomNavigationController.m and Implement two methods  as 
  

-(BOOL)shouldAutorotate
{
    return YES;
  
}


-(NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskAll;

}

8) Now every view of your app supports auto rotating.


Note: If you want to auto rotate only one view than

In CustomNavigationController.m modify the code as 



-(BOOL)shouldAutorotate
{
    //return YES;
    return [self.navigationController.topViewController shouldAutorotate];
  
}

in this case you should implement    

 -(BOOL)shouldAutorotate
{
     return YES;
}

in viewcontroller which u want to rotate.














Thursday, November 1, 2012

How to attach PDF file In e-mail

Get contacts of all your emergency needs on single tap. Download Quick-Finder for iPhone



MFMailComposeViewController *picker=[[MFMailComposeViewController alloc] init];
picker.mailComposeDelegate = self;
[picker setSubject:@"PDF File"]; 



 NSArray *toRecipients = [NSArray    arrayWithObjects:@"abc@example.com",nil];
 NSArray *ccRecipients = [NSArray arrayWithObjects:@"def@example.com", nil]; 
 NSArray *bccRecipients = [NSArray arrayWithObject:@"ghi@example.com"];
 [picker setToRecipients:toRecipients];
 [picker setCcRecipients:ccRecipients];
 [picker setBccRecipients:bccRecipients];

 // Attach an pdf to the email


// if it is in your NSBundle Use the following two lines


NSString *path = [[NSBundle mainBundle] pathForResource:@"Attachment" ofType:@"pdf"]; NSData *myData = [NSData dataWithContentsOfFile:path]; [picker addAttachmentData:myData mimeType:@"pdf" fileName:@"Attachment.pdf"]; 


// if it is in user documents Use the following two lines of code


NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString * path = [[paths lastObject] stringByAppendingPathComponent:@"Attachment.pdf"];



// Fill out the email body text

 NSString *emailBody = @"A PDF File is attached.";
 [picker setMessageBody:emailBody isHTML:NO];
 [self presentModalViewController:picker animated:YES];
 [picker release];       // No need if you are using iOS5+