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
2 Answers
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:©Error]) {
NSLog(@"Error copying files: %@", [copyError localizedDescription]);
}
-
By the way on this, because it might not be readily apparent, you need user permissions on the process that runs this.– VolomikeMar 14, 2016 at 16:20
-
While this answers part of the question, it omits the other part where existing contents of target directory (that is not present in source) is to be preserved.– matmJul 28, 2020 at 8:38
-
Sure, if that's what you want then you need to be more clever. But that's not what was asked ("Now I need to copy "temp" directory and all its contents to "main" folder (overwrite existing that was previously created)"), as also evidenced by this being the accepted answer.– jrtc27Sep 7, 2020 at 17:53
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:
.
-
1I used copyItemAtPath method of file manager. Yes it did copy files but it left all the directory at that level. I want everything to be copied in the dir structure. Any pointers ?– AlixAug 31, 2015 at 19:05
-
@Alix Whether I run
copyItemAtPath
ormoveItemAtPath
, it creates a directory by the pathname you specify if it does not exist. So, if I created /tmp/src and then wanted to copy into /tmp/dest, or move it into /tmp/dest, if I run jrtc27's solution, it will automatically delete any previous /tmp/dest and then copy it into /tmp/dest. As another example, let's say I have /tmp/Alix and a folder like /home/alix/Documents and I want to put an Alix folder in there. Fine -- I just set source to /tmp/Alix and dest. to /home/alix/Documents/Alix. It will automatically create the Alix folder for you.– VolomikeMar 14, 2016 at 16:58