Sunday, January 15, 2012

File Operation On Document Directory - iPhone SDK


- (void)copyCategoryToDocumentPath:(NSString *)fileName {
    NSFileManager *fileManager = [NSFileManager defaultManager];
        NSError *error;
        NSString *path = [self getDocumentPathWithFileName:fileName];
        BOOL fileExist = [fileManager fileExistsAtPath:path]
        
        if(!fileExist){
                
                NSString *defaultPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:fileName];
                BOOL fileTransfered = [fileManager copyItemAtPath:defaultPath toPath:path error:&error];
                
                if (!fileTransfered) 
                        NSAssert1(0@"Failed to create writable database file with message '%@'."[error localizedDescription]);
        }
}

- (NSString *)getDocumentPathWithFileName:(NSString *)fileName {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
        NSString *documentsDir = [paths objectAtIndex:0];
        return [documentsDir stringByAppendingPathComponent:fileName];
}


NString *newDirectoryName = @"<new folder name>";    
NSString *oldPath = @"<path to the old folder>";
NSString *newPath = [[oldPath stringByDeletingLastPathComponent] stringByAppendingPathComponent:newDirectoryName];
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:oldPath toPath:newPath error:&error];
if (error) {
    NSLog(@"%@",error.localizedDescription);
    // handle error
}