Issue 1: The issue occurred because, the directory already contains a file with same file name.
You should check whether the file exist in the folder or not like:
- (void)saveFile:(NSString *)folderPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"destination.png"];
NSError *error = nil;
NSString *srcPath = [folderPath stringByAppendingPathComponent:@"filename.png"];
if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath])
{
//removing file
if (![[NSFileManager defaultManager] removeItemAtPath:dataPath error:&error])
{
NSLog(@"Could not remove old files. Error:%@",error);
}
}
BOOL success = [[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:dataPath error:&error];
if (success == YES)
{
NSLog(@"Copied");
}
else
{
NSLog(@"Not Copied %@", error);
}
}
Issue 2: You must provide a file name not a directory.
Replace:
BOOL success = [[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:documentsDirectory error:&error];
With:
BOOL success = [[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:dataPath error:&error];