Jaume
Jaume

Reputation: 923

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);;
        }
    }
}

Upvotes: 11

Views: 7549

Answers (2)

Ignacio Inglese
Ignacio Inglese

Reputation: 2605

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.

Upvotes: 6

cli_hlt
cli_hlt

Reputation: 7164

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).

Upvotes: 2

Related Questions