Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSFileManager - Copying Files at Startup

I need to copy a few sample files from my app's resource folder and place them in my app's document folder. I came up with the attached code, it compiles fine but it doesn't work. All the directories I refer to do exist. I'm not quite sure what I am doing wrong, could someone point me in the right direction please?

NSFileManager*manager = [NSFileManager defaultManager];

NSString*dirToCopyTo = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

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

NSString*dirToCopyFrom = [path stringByAppendingPathComponent:@"Samples"];


NSError*error;

NSArray*files = [manager contentsOfDirectoryAtPath:dirToCopyFrom error:nil];

for (NSString *file in files)
{
        [manager copyItemAtPath:[dirToCopyFrom stringByAppendingPathComponent:file] toPath:dirToCopyTo error:&error];

        if (error)
        {
            NSLog(@"%@",[error localizedDescription]);
    }
}

EDIT: I just edited the code the way it should be. Now however there's another problem:

2010-05-15 13:31:31.787 WriteIt Mobile[4587:207] DAMutableDictionary.h 2010-05-15 13:31:31.795 WriteIt Mobile[4587:207] FileManager Error:Operation could not be completed. File exists

EDIT : I have fixed the issue by telling NSFileManager the names of the copied files's destinations.

        [manager copyItemAtPath:[dirToCopyFrom stringByAppendingPathComponent:file] toPath:[dirToCopyTo stringByAppendingPathComponent:file] error:&error];
like image 408
Pripyat Avatar asked Dec 28 '22 16:12

Pripyat


1 Answers

I think the problem is in this line:

NSArray*files = [manager contentsOfDirectoryAtPath:dirToCopyTo error:nil];

You are listing files in a destination directory instead of the source. Change it to something like:

NSArray*files = [manager contentsOfDirectoryAtPath:dirToCopyFrom error:nil];

And you should be fine.

like image 181
Eimantas Avatar answered Jan 12 '23 23:01

Eimantas