My Blog List

Android FirstAid Coding

A Small Help From a Small Heart
Powered by Blogger.

A software professional, who still likes to code, likes to blog and loves gadgets.

Wednesday, 26 June 2013

File management in iPhone

This topic is based on file management in iPhone.Here is the code snippet which
able to perform below action.

    •    Creating a folder in document directory

    •    Creating folder within folder(subfolder) inside document directory
    •    Copy file from Nsbundle to Document directory
    •    Access the contents of a document folder
    •    Access the file name,file path & file updated time of a document folder
    •    Copy a file from one folder to another folder within document directory
    •    Delete a file
    •    Move the contents of a folder to another folder within document directory  

How to view the file system on the iOS simulater?

open finder => Go =>(Then click "Alt" key to see the "Library") => Library => Application Support => iPhone Simulator

It has directories for all models of simulators (4.0, 4.1, 5.0, etc) you have ever run, go to the one you are running from in Xcode.
Once in a folder, go to Applications, choose the Finder option that shows date for files, and sort by date. Your application will be the most recent since it just changed the directory.
Inside the directory is everything related to your application.


Creating a folder in document directory
-(void)createFolder{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"Raju"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
       
        NSError* error;
        if(  [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]){
            UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"Folder Created Successfully" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [Alert show];
        }                  
        else
        {
            NSLog(@"[%@] ERROR: attempting create raju directory", [self class]);
            NSAssert( FALSE, @"Failed to create directory maybe out of disk space?");
        }
    }
}


Creating folder within folder(subfolder) inside document directory

-(void)createSubFolder{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"Raju1/Raju2/Raju3"];
    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
       
        NSError* error;
        if(  [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&error]){
            UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"Folder Created Successfully" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [Alert show];
        }                  
        else
        {
            NSLog(@"[%@] ERROR: attempting create raju directory", [self class]);
            NSAssert( FALSE, @"Failed to create directory maybe out of disk space?");
        }
    }
}

Copy file from Nsbundle to Document directory

-(void)copyNsbundleFile{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *storePath = [documentsDirectory stringByAppendingPathComponent:@"Raju/myphoto.jpg"];
   
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:storePath]) {
        NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"me1" ofType:@"jpg"];
       
        if (defaultStorePath) {
            NSError* error;
            if(  [fileManager copyItemAtPath:defaultStorePath toPath:storePath error:&error]){
                UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"File Copied Successfully" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
                [Alert show];
            }                  
            else
            {
                NSLog(@"[%@] ERROR: attempting create raju directory", [self class]);
                NSAssert( FALSE, @"Failed to create directory maybe out of disk space?");
            }
           
        }
    }
}






Access the contents of a document folder

-(void)contentOfFolder{
    NSError* error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:@"Raju"];
   
    NSArray* filesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error];
    NSLog(@"conent of a folder===%@",filesArray);
}






Access the file name,file path & file updated time of a document folder


-(void)contentOfFolderWithFileInfo{
    NSError* error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *folderPath = [documentsDirectory stringByAppendingPathComponent:@"Raju"];
   
    NSArray* filesArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:folderPath error:&error];
    //NSLog(@"conent of a folder===%@",filesArray);
    for(NSString* file in filesArray) {
        NSString* filePath = [folderPath stringByAppendingPathComponent:file];
       
        NSDictionary* properties = [[NSFileManager defaultManager]
                                    attributesOfItemAtPath:filePath
                                    error:&error];
        NSDate* modDate = [properties objectForKey:NSFileModificationDate];
        NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
        [dateFormatter1 setDateFormat:@"dd/MM/YY HH:mm"];
        NSLog(@"File Name==%@",file);
        NSLog(@"File update date==%@",[dateFormatter1 stringFromDate:modDate]);
        NSLog(@"File Path==%@",filePath);
       
    } 
}




Copy a file from one folder to another folder within document directory

-(void)copyFile{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *actualImagePath = [documentsDirectory stringByAppendingPathComponent:@"Raju/myphoto.jpg"];
    NSString *copyImagePath = [documentsDirectory stringByAppendingPathComponent:@"Meera/Adi"];
    NSError* error;
    if (![[NSFileManager defaultManager] fileExistsAtPath:copyImagePath]){     
        if(  [[NSFileManager defaultManager] createDirectoryAtPath:copyImagePath withIntermediateDirectories:YES attributes:nil error:&error]){           
        }                  
        else
        {
            NSLog(@"[%@] ERROR: attempting create directory", [self class]);
            NSAssert( FALSE, @"Failed to create directory maybe out of disk space?");
        }
    }
    NSFileManager *manager = [NSFileManager defaultManager];   
    if([manager copyItemAtPath:actualImagePath toPath:[NSString stringWithFormat:@"%@/myphoto.jpg",copyImagePath] error:&error]==NO)
    {
        UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"Error" message:[NSString stringWithFormat:@"%@",[error userInfo]] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [Alert show];
    }else {
       
        NSLog(@"image copied");
       
    }
}


Delete a file

-(void)removeFolder{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *deleteFolderPath = [documentsDirectory stringByAppendingPathComponent:@"Meera/Adi"];
    NSError* error;
    NSFileManager *manager = [NSFileManager defaultManager];   
   
    if(![manager removeItemAtPath: deleteFolderPath error:&error]) {
        NSLog(@"Delete failed:%@", error);
    } else {
        NSLog(@"folder removed: %@", deleteFolderPath);
    }
    UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"File Moved Successfully" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
    [A
lert show];
}


Move the contents of a folder to another folder within document directory

-(void)moveFile{
    NSError *error=nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *existingFolderPath = [documentsDirectory stringByAppendingPathComponent:@"Raju"];
   
    NSString *toPath = [documentsDirectory stringByAppendingPathComponent:@"Meera"];//folder named meera already exist in my case
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![[NSFileManager defaultManager] fileExistsAtPath:toPath]){     
        if(  [[NSFileManager defaultManager] createDirectoryAtPath:toPath withIntermediateDirectories:NO attributes:nil error:&error]){           
        }                  
        else
        {
            NSLog(@"[%@] ERROR: attempting create directory", [self class]);
            NSAssert( FALSE, @"Failed to create directory maybe out of disk space?");
        }
    }
   
    NSArray *allImagePath = [manager contentsOfDirectoryAtPath:existingFolderPath error:nil];
    for (NSString *onepath in allImagePath){
        NSString *actualImagePath=[NSString stringWithFormat:@"%@/%@",existingFolderPath,onepath];
        if ([manager moveItemAtPath:actualImagePath toPath:[NSString stringWithFormat:@"%@/%@",toPath,onepath] error:&error] != YES)
        {
            UIAlertView *Alert=[[UIAlertView alloc]initWithTitle:@"Error" message:[NSString stringWithFormat:@"%@",[error userInfo]] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
            [Alert show];
        }else {
           
            NSLog(@"File Moved");
        }
    }
}


Download Project

Monday, 10 June 2013

Keyboard hides UITextField in iphone

This is an easy solution of the problem like keyboard hides UITextField in IOS.
Just refer your UITextField to its delegate and object in .xib file and write down the following code.

ViewController.h
================
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextFieldDelegate>{
    IBOutlet UITextField *nameTf,*addressTf;
}

@end


ViewController.m
================
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
   
}

- (void)viewDidUnload
{
    [super viewDidUnload];
   
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
   
}
- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
   
    int movementDistance=0;
    const float movementDuration = 0.3f;
  
    if (textField == nameTf) {
        movementDistance = 200;//you can change this value
    }else if (textField == addressTf) {
        movementDistance = 210;//you can change this value
    }
    int movement = (up ? -movementDistance : movementDistance);
    [UIView beginAnimations: @"anim" context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    self.view.frame = CGRectOffset(self.view.frame, 0, movement);
    [UIView commitAnimations];
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [self animateTextField: textField up: NO];
}

@end
 


UITextField within UITableView in iPhone

CreateCustomer.h
============= 

//
//  CreateCustomer.h
//  demo
//
//  Created by Rajendra Nayak on 10/06/13.
//  Copyright (c) 2013 rajuandroid.blogspot.com Apps. All rights reserved.
//

#import <UIKit/UIKit.h>
@interface CreateCustomer : UITableViewController<UITextFieldDelegate>{
    NSString *fName,*lName,*email,*password,*confirmPassword;
 
}

@property(nonatomic,retain) NSString *name,*phone,*email,*address;

@end


CreateCustomer.m
============= 
//
//  CreateCustomer.m
//  demo
//
//  Created by Rajendra Nayak on 10/06/13.
//  Copyright (c) 2013 rajuandroid.blogspot.com Apps. All rights reserved.
//

#import "CreateCustomer.h"


@interface CreateCustomer ()

@end

@implementation CreateCustomer
@synthesize className;
@synthesize name,phone,email,address;
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.hidesBackButton = YES;
    [self.tableView setScrollEnabled:NO];
    self.navigationItem.title=@"Customer";
    self.name=@"";self.email=@"";self.phone=@"";self.address=@"";
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 2;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section==0) {
        return 4;
    }else {
        return 1;
    }
   
}

- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    static NSString *CellIdentifier = @"Cell";
   
    UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
   
    if ([indexPath section] == 0) {
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(7, 0, cell.contentView.bounds.size.width - 27, cell.contentView.bounds.size.height)];
        [textField setContentVerticalAlignment:UIControlContentVerticalAlignmentCenter];
        [textField setAutocorrectionType:UITextAutocorrectionTypeNo];
        [textField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
        [textField setBorderStyle:UITextBorderStyleNone];
        [textField setClearButtonMode:UITextFieldViewModeWhileEditing];
        textField.delegate=self;
       
        if (indexPath.row == 0) {
            [textField setAutocapitalizationType:UITextAutocapitalizationTypeWords];          
            [textField setPlaceholder:@"Name"];
           
        }
        else if (indexPath.row == 1) {
            [textField setPlaceholder:@"Email"];
            [textField setKeyboardType:UIKeyboardTypeEmailAddress];
            // [textField becomeFirstResponder];
           
        }else if (indexPath.row == 2) {
            [textField setPlaceholder:@"Phone"];          
            [textField setKeyboardType:UIKeyboardTypePhonePad];
           
        } else {
            [textField setPlaceholder:@"Address"];           
            [textField setKeyboardType:UIKeyboardTypeDefault];
           
        }
        [cell.contentView addSubview:textField];
        [textField release];
    }else { // Login button section
        cell.textLabel.text = @"Create Customer";
        cell.textLabel.textAlignment=UITextAlignmentCenter;
        cell.textLabel.textColor=[UIColor brownColor];
    }
   
   
    return cell;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
   
    [textField resignFirstResponder];
   
    return YES;
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    UITableViewCell *cell = (UITableViewCell *)[[textField superview] superview];
    UITableView *table = (UITableView *)[cell superview];
    NSIndexPath *textFieldIndexPath = [table indexPathForCell:cell];
    if (textFieldIndexPath.section==0) {
        if (textFieldIndexPath.row == 0) {
            self.name=textField.text;
        }
        else if (textFieldIndexPath.row == 1) {
            self.email=textField.text;
        }else if (textFieldIndexPath.row == 2) {
            self.phone=textField.text;
        }else if (textFieldIndexPath.row == 3) {
            self.address=textField.text;
        }
    }
   
   
   
}
-(IBAction)registerButtonPressed{
    [self.view endEditing:YES];
    NSLog(@"name==%@",self.name);       
}
@end




Tuesday, 28 May 2013

Showing UIPickerView inside UIPopoverController


ViewController.h
=============
#import <UIKit/UIKit.h>


@interface ViewController : UIViewController<UIPickerViewDelegate, UIPickerViewDataSource>{
    int selectedProductTypeSrcIndex;  
    NSString *selectedProductType;  
    IBOutlet UIButton *productTypeOption;  
}
@property(nonatomic,retain) NSArray *productTypeSrc;
@property(nonatomic,retain) UIPickerView *myPickerView;
@property(nonatomic,retain) UIPopoverController *popoverController;
- (IBAction)showOptionAction:(id)sender;

@end



ViewController.m
================

//
// ViewController.m
// PickerDemo
//
// Created by Rajendra on 27/05/13.
// Copyright (c) 2013 RajuAndroid.blogspot.com. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController


@synthesize myPickerView,popoverController;
@synthesize productTypeSrc;
- (void)viewDidLoad

{

[super viewDidLoad];
self.productTypeSrc = [NSArray arrayWithObjects:@"Collison Damage Waive",@"Deposit Waiver",@"Excess Reduction Waiver",@"Malaysian Travel Charges Waiver",@"Penalty Waiver",nil];
selectedProductTypeSrcIndex=0;

}

- (IBAction)showOptionAction:(id)sender{
UIView *masterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 260)];
UIToolbar *pickerToolbar = [self createPickerToolbarWithTitle:@"Title"];
[pickerToolbar setBarStyle:UIBarStyleBlackTranslucent];
[masterView addSubview:pickerToolbar];
CGRect pickerFrame = CGRectMake(0, 40, 300, 216);
UIPickerView *myPicker = [[UIPickerView alloc] initWithFrame:pickerFrame];
[myPicker setDataSource: self];
[myPicker setDelegate: self];
myPicker.tag=1;
[myPicker selectRow:0 inComponent:0 animated:NO];
[myPicker setShowsSelectionIndicator:YES];
self.myPickerView=myPicker;
[masterView addSubview:myPicker];
UIViewController *viewController = [[UIViewController alloc] initWithNibName:nil bundle:nil];
viewController.view = masterView;
viewController.contentSizeForViewInPopover = viewController.view.frame.size;
self.popoverController =[[UIPopoverController alloc] initWithContentViewController:viewController];
UIButton *button = (UIButton *)sender;
[self.popoverController presentPopoverFromRect:button.bounds
inView:button
permittedArrowDirections:UIPopoverArrowDirectionDown
animated:YES];

}

- (UIToolbar *)createPickerToolbarWithTitle:(NSString *)title {

CGRect frame = CGRectMake(0, 0, 300, 44);
UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:frame];
pickerToolbar.barStyle = UIBarStyleBlackOpaque;
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *cancelBtn = [self createButtonWithType:UIBarButtonSystemItemCancel target:self action:@selector(actionPickerCancel:)];
[barItems addObject:cancelBtn];
UIBarButtonItem *flexSpace = [self createButtonWithType:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

[barItems addObject:flexSpace];
if (title){
UIBarButtonItem *labelButton = [self createToolbarLabelWithTitle:title];
[barItems addObject:labelButton];
[barItems addObject:flexSpace];
}
UIBarButtonItem *doneButton = [self createButtonWithType:UIBarButtonSystemItemDone target:self action:@selector(actionPickerDone:)];
[barItems addObject:doneButton];
[pickerToolbar setItems:barItems animated:YES];
return pickerToolbar;

}

- (IBAction)actionPickerDone:(id)sender {

//[self notifyTarget:self.target didSucceedWithAction:self.successAction origin:[self storedOrigin]];

if (self.popoverController && self.popoverController.popoverVisible)
[self.popoverController dismissPopoverAnimated:YES];

}

- (IBAction)actionPickerCancel:(id)sender {

if (self.popoverController && self.popoverController.popoverVisible)
[self.popoverController dismissPopoverAnimated:YES];

}

- (UIBarButtonItem *)createToolbarLabelWithTitle:(NSString *)aTitle {

UILabel *toolBarItemlabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 180,30)];
[toolBarItemlabel setTextAlignment:UITextAlignmentCenter];
[toolBarItemlabel setTextColor:[UIColor whiteColor]];
[toolBarItemlabel setFont:[UIFont boldSystemFontOfSize:16]];
[toolBarItemlabel setBackgroundColor:[UIColor clearColor]];
toolBarItemlabel.text = aTitle;
UIBarButtonItem *buttonLabel = [[UIBarButtonItem alloc]initWithCustomView:toolBarItemlabel];
return buttonLabel;

}

- (UIBarButtonItem *)createButtonWithType:(UIBarButtonSystemItem)type target:(id)target action:(SEL)buttonAction {

return [[UIBarButtonItem alloc] initWithBarButtonSystemItem:type target:target action:buttonAction];

}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;

{

return 1;

}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;

{

if ([pickerView tag] == 1) {
return [self.productTypeSrc count];
}
return 0;

}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;

{
if ([pickerView tag] == 1) {
return [self.productTypeSrc objectAtIndex:row];

}

return @"";

}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component

{

if ([pickerView tag] == 1) {
selectedProductTypeSrcIndex=row;
selectedProductType=[self.productTypeSrc objectAtIndex:selectedProductTypeSrcIndex];
[productTypeOption setTitle:selectedProductType forState:UIControlStateNormal];

}

}

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

@end


 
 

Wednesday, 1 May 2013

How to store custom objects in NSUserDefaults in Iphone

Situation
=============

  • I am storing Custom object in NSMutableArray
  • then storing NSMutableArray into NSMutableDictionary.
  • Where Key of NSMutableDictionary is a unique_foldername(NSString) and value of NSDictionary is a NSMutableArray.
Question
==============
  • Now how can i store NSMutableDictionary in NSUserDefaults ?
  • Now how can i retrieve NSMutableDictionary from NSUserDefaults?
Solution
==============

DocumentVo.h
-----------------
#import <UIKit/UIKit.h>

@interface DocumentVo : NSObject{
    NSString *docName,*docUpdatedTime,*docImage;
    int docCount;
}
@property (nonatomic, retain) NSString *docName,*docUpdatedTime,*docImage;
@property (nonatomic) int docCount;
@end

DocumentVo.m
----------------- 
#import "DocumentVo.h"

@implementation DocumentVo
@synthesize docName,docUpdatedTime,docCount,docImage;

- (void)encodeWithCoder:(NSCoder *)encoder {
    //Encode properties, other class variables, etc
    [encoder encodeObject:self.docName forKey:@"docName"];
    [encoder encodeObject:self.docUpdatedTime forKey:@"docUpdatedTime"];
   
    [encoder encodeInt:self.docCount forKey:@"docCount"];
    [encoder encodeObject:self.docImage forKey:@"docImage"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    if((self = [super init])) {
        //decode properties, other class vars
        self.docName = [decoder decodeObjectForKey:@"docName"];
        self.docUpdatedTime = [decoder decodeObjectForKey:@"docUpdatedTime"];
        self.docCount = [decoder decodeIntForKey:@"docCount"];
        self.docImage = [decoder decodeObjectForKey:@"docImage"];
    }
    return self;
}
- (void) dealloc {
    [docName release];
    [docUpdatedTime release];
    //[docCount release];
    [docImage release];
    [super dealloc];
}

@end
 

 Saving Object
---------------------

    NSString *rootFolderName;
    NSUserDefaults *defauktCenter = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *allFolderWithImageDict=[NSMutableDictionary dictionary];
    NSMutableDictionary *resultDictionary = [NSKeyedUnarchiver unarchiveObjectWithData:respData];
    NSMutableArray *docArray=[[NSMutableArray alloc] init];   
    DocumentVo *docVo=[[DocumentVo alloc] init];
    docVo.docCount=1;
    docVo.docName=@"FolderName";
    docVo.docUpdatedTime=@"12:23";
    docVo.docImage=@"FolderName/myfilename";
    [docArray addObject:docVo];  
  
    [allFolderWithImageDict setValue:docArray forKey:rootFolderName];  
    NSData *myEncodedObject = [NSKeyedArchiver     archivedDataWithRootObject:allFolderWithImageDict];  
    [defauktCenter setValue:myEncodedObject forKey:@"FolderImageDict"];
    [defauktCenter synchronize];


  Retrieving Object

--------------------------
    NSData *respData1 = [[NSUserDefaults standardUserDefaults] objectForKey:@"FolderImageDict"];
    NSMutableDictionary *resultDictionary1 = [NSKeyedUnarchiver unarchiveObjectWithData:respData1];
 
    NSArray * array= [resultDictionary1 objectForKey:rootFolderName] ;
    DocumentVo *docVo1=[array objectAtIndex:0];
    NSLog(@"docVo.docCount==%d",docVo1.docCount);
    NSLog(@"docVo.docName==%@",docVo1.docName);
    NSLog(@"docVo.docUpdatedTime==%@",docVo1.docUpdatedTime);
    NSLog(@"docVo.docImage==%@",docVo1.docImage);





 

Monday, 29 April 2013

UIMenuController in iphone

NOTE:
UIMenuController will only work if it becomes the first responder

- (void)viewDidLoad
{
    [super viewDidLoad];  
    UIBarButtonItem *addJobButton = [[UIBarButtonItem alloc] initWithTitle:@"Add Contacts" style:UIBarButtonSystemItemAdd
                                                                    target:self action:@selector(setAddContactTapped:event:)];
    self.navigationItem.rightBarButtonItem = addJobButton;
    [addJobButton release];
}
-(void)setAddContactTapped:(id)sender event:(UIEvent*)event{
    [self becomeFirstResponder];
     /*get the view from the UIBarButtonItem*/
    UIView *buttonView=[[event.allTouches anyObject] view];
    CGRect buttonFrame=[buttonView convertRect:buttonView.frame toView:self.view];
   
    UIMenuController *menuController = [UIMenuController sharedMenuController];
    UIMenuItem *personMenuItem = [[UIMenuItem alloc] initWithTitle:@"Person" action:@selector(newPerson:)];
    UIMenuItem *companyMenuItem = [[UIMenuItem alloc] initWithTitle:@"Company" action:@selector(newCompany:)];
   
   // NSAssert([self becomeFirstResponder], @"Sorry, UIMenuController will not work with %@ since it cannot become first responder", self);
    menuController.menuItems = [NSArray arrayWithObjects: personMenuItem, companyMenuItem, nil];  
    [menuController setTargetRect:buttonFrame inView:self.view];
    [menuController setMenuVisible:YES animated:YES];
    [personMenuItem release];
    [companyMenuItem release];      
}

- (void) newPerson: (UIMenuController*) sender
{
 //Add you logic
}
- (void) newCompany: (UIMenuController*) sender
{ 
    //Add your logic
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    BOOL can = [super canPerformAction:action withSender:sender];
    if (action == @selector(
newPerson:) || action == @selector(newCompany:))
    {
        can = YES;
    }
    if (action == @selector(copy:))
    {
        can = NO;
    }
   return can;
}
- (BOOL) canBecomeFirstResponder {
    return YES;
}


Showing Activity Indicator Within UIAlertview in Iphone

ViewController.h
================

@interface ViewController : UIViewController{
    UIAlertView *alertLoader;
}

@end

ViewController.m
================

- (void)viewDidLoad
{
    [super viewDidLoad];  
    [self methodtocallWebservices];
}
-(void)methodtocallWebservices{   
    alertLoader = [[UIAlertView alloc] initWithTitle:@"" message:@"Please Wait..." delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    alertLoader.tag=1;
    [alertLoader show];   
}
- (void)didPresentAlertView:(UIAlertView *)alertView
{  
    if (alertView.tag== 1) {
        UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];       
        indicator.center = CGPointMake(alertView.bounds.size.width/2, alertView.bounds.size.height/3 * 2);       
        [indicator startAnimating];
        [alertView addSubview:indicator];       
        NSString *hostStr = @"@"http://rajuandroid.blogspot.com/api/contact_name_json";       
        NSURL *url = [[NSURL alloc] initWithString:hostStr];
        NSLog(@"login url:  %@",url);       
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
        [url release];
    }   
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
  //  [self.receivedData appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    [self stopLoading];
    //[self handleError:error];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    [self stopLoading];  
}
-(void)stopLoading
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [alertLoader dismissWithClickedButtonIndex:0 animated:YES];
        [alertLoader release];
    });
}