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

No comments:

Post a Comment