Tuesday, October 11, 2011

Working with Resources Directory in XCode and Document Directory in iPhone



  1. Copy File from Resources folder to Document Directory

    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];

        // Copy eCommerce.sqlite3 from resources to the Documents folder
    NSString *storePath = [documentsDirectory stringByAppendingPathComponent: @"eCommerce.sqlite3"];
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"eCommerce" ofType:@"sqlite3"];
    if (filePath) {
        NSData *myData = [NSData dataWithContentsOfFile:filePath];
        if (![myData writeToFile:storePath atomically:YES]) {
            [self handleError:@"Critical file creation on the disk failed unexpectedly! Please leave the application as this is unrecoverable.!"];
        }
    }else {
        [self handleError:@"there is no database in Resources Folder!"];
    }


  
      2.  Check whether Existing file is there or not in Document directory


    NSString *getDatabasePath = [documentsDirectory stringByAppendingString:@"/eCommerce.sqlite3"];
   
    NSFileManager* fileManager = [NSFileManager defaultManager];
    if(![fileManager fileExistsAtPath:getDatabasePath])  {
        NSLog(@"file doesn't exist");
            // file doesn't exist
    } else {
         NSLog(@"file exist");
    }



      3. Create a Folder in side Document directory

- (void)createFolder:(NSString*)folderName
{
    NSString *storePath = [self.documentsDirectory stringByAppendingPathComponent:folderName];
    NSFileManager *NSFm= [NSFileManager defaultManager];

//        if(![NSFm createDirectoryAtPath:storePath attributes:nil])
//            [self handleError:@"Critical file creation on the disk failed unexpectedly! Please leave the application as this is unrecoverable.!"];

    if(![NSFm createDirectoryAtPath:storePath withIntermediateDirectories:YES attributes:nil error:NULL])
        [self handleError:@"Critical file creation on the disk failed unexpectedly! Please leave the application as this is unrecoverable.!"];
   
}
 

      4. Delete a file in side Document directory

    NSFileManager *fm = [NSFileManager defaultManager];     // delete zip file
            [fm removeItemAtPath:storePath error:nil];
            [fm removeItemAtPath:[documentsDirectory stringByAppendingPathComponent: @"__MACOSX"] error:nil];