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