Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS copy files from main bundle to documents directory

I am trying to copy files that I add to a folder called "includes" to a folder on documents directory called also "includes".

I get a nil value for resContents. Why?

- (void)copyResources{

    NSString *sourcePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"includes"];
    NSString *destPath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:@"includes"];

    NSArray* resContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:sourcePath error:NULL];

    for (NSString* obj in resContents){
        NSError* error;
        if (![[NSFileManager defaultManager] copyItemAtPath:[sourcePath stringByAppendingPathComponent:obj] toPath:[destPath stringByAppendingPathComponent:obj] error:&error]) {
            NSLog(@"Error: %@", error);;
        }
    }
}
like image 660
Jaume Avatar asked Feb 10 '12 15:02

Jaume


2 Answers

Your Xcode project should add your includes folder as a Folder Reference and not as a Group.

Groups are just meant to keep things organized rather than provide a folder structure and therefore when copying to the device, all the files end up at the same level.

like image 197
Ignacio Inglese Avatar answered Oct 29 '22 00:10

Ignacio Inglese


Look into your compiled application bundle.

Usually, the Xcode generated bundles are flat. This means although your added resource files will be copied to the bundle, any directories you created will not and hence there is no "includes" directory at the resource path. Consequently, your source contents will be nil.

So in your case, try using just:

NSString *sourcePath = [[NSBundle mainBundle] resourcePath];

Edit: Well and obviously adding a folder reference also works (credits to Ignacio Inglese).

like image 31
cli_hlt Avatar answered Oct 28 '22 23:10

cli_hlt