Jaume
Jaume

Reputation: 923

iOS copy directories including subdirectories

I am working with iOS document folder called "temp" that allocates subdirectories that contain files dowloaded from remote url. Now I need to copy "temp" directory and all its contents to "main" folder (overwrite existing that was previously created). I know how to handle files but how to copy whole directory? Thank you

Upvotes: 17

Views: 13169

Answers (2)

jrtc27
jrtc27

Reputation: 8526

You can use the same NSFileManager methods that you know and love for directories as well. For example:

if ([[NSFileManager defaultManager] fileExistsAtPath:pathToTempDirectoryInMain]) {
    [[NSFileManager defaultManager] removeItemAtPath:pathToTempDirectoryInMain error:nil];
}
NSError *copyError = nil;
if (![[NSFileManager defaultManager] copyItemAtPath:pathToTempDirectory toPath:pathToTempDirectoryInMain error:&copyError]) {
    NSLog(@"Error copying files: %@", [copyError localizedDescription]);
}

Upvotes: 29

rob mayoff
rob mayoff

Reputation: 385600

The NSFileManager methods removeItemAtPath:error:, removeItemAtURL:error:, copyItemAtPath:toPath:error:, and copyItemAtURL:toURL:error: methods handle directories.

You might also look at moveItemAtPath:toPath:error: and moveItemAtURL:toURL:error:.

Upvotes: 5

Related Questions