iPhone: Error in copyItemAtPath - ios

I am trying to copy a file from one folder to another folder in documents directory like this:
- (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"];
BOOL success = [[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:documentsDirectory error:&error];
if (error)
{
NSLog(#"%#",error);
}
if (success == YES)
{
NSLog(#"Copied");
}
else
{
NSLog(#"Not Copied");
}
}
When i log error, it gives me the following message:
Error Domain=NSCocoaErrorDomain Code=516 "The operation couldn’t be completed. (Cocoa error 516.)" UserInfo=0x9d665a0 {NSUserStringVariant=(
Move
), NSFilePath=/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/BC37C9D7-7995-47C1-8131-2B07BADCBECB/Documents/foldername/B713320C-2CA0-4FD3-93F6-71D76B102B83/src.png, NSDestinationFilePath=/Users/username/Library/Application Support/iPhone Simulator/5.1/Applications/BC37C9D7-7995-47C1-8131-2B07BADCBECB/Documents, NSUnderlyingError=0x9d41c60 "The operation couldn’t be completed. File exists"}

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];

copyItemAtPath: is giving error as that file is already exist in that location. So you should do this before you copy file.
if ([[NSFileManager defaultManager] fileExistsAtPath: srcPath])
[[NSFileManager defaultManager] removeItemAtPath: srcPath error:nil];

Replace this line:
BOOL success = [[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:documentsDirectory error:&error];
With:
BOOL success = [[NSFileManager defaultManager] copyItemAtPath:srcPath toPath:dataPath error:&error];

Related

Sometime ERROR copy file from bundle to documents directory in iOS

I am trying to copy a file from my bundle to the documents directory in iOS with the following code.
code:
- (NSString*)getModuleHome{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[[paths objectAtIndex:0] stringByAppendingPathComponent:#"webapp" ]stringByAppendingPathComponent:#"modules"];
return path;
}
- (void)FirstLoad{
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:[self getModuleHome]]) {
//建立目录
[[NSFileManager defaultManager] createDirectoryAtPath:[self getModuleHome] withIntermediateDirectories:YES attributes:nil error:nil];
}
NSUserDefaults *userDef = [NSUserDefaults standardUserDefaults];
BLYLogInfo(#"FirstLoad");
NSString *zipPath = [[NSBundle mainBundle] pathForResource:#"" ofType:#"zip"];
NSString *path = NSTemporaryDirectory();
NSString *dataPath = [path stringByAppendingPathComponent:#"modules.zip"];
if ([[NSFileManager defaultManager] fileExistsAtPath:dataPath]) {
BLYLogInfo(#"fileExistsAtPath dataPath");
[[NSFileManager defaultManager] removeItemAtPath:dataPath error:&error];
}
if(![[NSFileManager defaultManager] copyItemAtPath:zipPath toPath:dataPath error:&error])
{
BLYLogError(#"Error copying files: %#", [error localizedDescription]);
[Bugly reportError:error];
}
BLYLogInfo(#"FirstLoad Unzip");
NSString *unZipPath = [path stringByAppendingPathComponent: #"modules"];
if ([[NSFileManager defaultManager] fileExistsAtPath:unZipPath]) {
[[NSFileManager defaultManager] removeItemAtPath:unZipPath error:&error];
}
[SSZipArchive unzipFileAtPath:dataPath toDestination:unZipPath];
BLYLogInfo(#"FirstLoad Copy");
NSString *destinationPath = [self getModuleHome];
BLYLogInfo(#"FirstLoad destinationPath:%#",destinationPath);
if ([[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) {
BLYLogWarn(#"FirstLoad removeItemAtPath");
[[NSFileManager defaultManager] removeItemAtPath:destinationPath error:&error];
}
if (![[NSFileManager defaultManager] copyItemAtPath:unZipPath toPath:destinationPath error:&error]) {
BLYLogError(#"FirstLoad Error copying files: %#", [error localizedDescription]);
[Bugly reportError:error];
NSLog(#"FirstLoad Clean");
[[NSFileManager defaultManager] removeItemAtPath:dataPath error:nil];
[[NSFileManager defaultManager] removeItemAtPath:unZipPath error:nil];
//加载出错
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView* view = [[UIAlertView alloc] initWithTitle:#"提示"
message:#"抱歉,资源加载失败,请关闭重试"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
[view show];
});
}
else{
BLYLogInfo(#"FirstLoad Clean");
[[NSFileManager defaultManager] removeItemAtPath:dataPath error:nil];
[[NSFileManager defaultManager] removeItemAtPath:unZipPath error:nil];
[userDef setObject:#"NO" forKey:#"UpdateFlag"];
[userDef synchronize];
[self FirstReload];
}
}
Attach Log:
User Data: NSErrorUserInfo: { NSDestinationFilePath =
"/var/mobile/Containers/Data/Application/3575F3DD-4DC7-4472-A3D0-D4FF86C40BEF/Documents/webapp/modules/ihub/img/cat.png";
NSFilePath =
"/private/var/mobile/Containers/Data/Application/3575F3DD-4DC7-4472-A3D0-D4FF86C40BEF/tmp/modules/ihub/img/cat.png";
NSSourceFilePathErrorKey =
"/private/var/mobile/Containers/Data/Application/3575F3DD-4DC7-4472-A3D0-D4FF86C40BEF/tmp/modules/ihub/img/cat.png";
NSUnderlyingError = "Error Domain=NSPOSIXErrorDomain Code=2 \"No such
file or directory\""; NSUserStringVariant = ( Copy ); }
The app has been released.
Most phones are normal.
Only some phones have this problem.
Each log file reported errors is not the same file not exist.
SAMPLE:
NSError(NSCocoaErrorDomain:4)The
file“contractpayment-detail.html”doesn’t exist。
NSError(NSCocoaErrorDomain:4)The file “vacating.png” doesn’t exist.
NSError(NSCocoaErrorDomain:4)The file “Mode.ts” doesn’t exist.
NSError(NSCocoaErrorDomain:4)The file “SystemCtrl.js” doesn’t exist.
"Why? How to fix it?"
plz try this code
//array of main bundle images
NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:#"admin_1454993109_restaurants_uploaded",
#"admin_1454993149_other_uploaded",
#"admin_1454993170_car_uploaded",
#"admin_1454993206_home_uploaded",
#"admin_1454993235_fashion_uploaded",
#"admin_1454993290_shirt_uploaded",
#"admin_1454993347_electronic_uploaded",
#"admin_1454993380_notes_uploaded", nil];
for (int i = 0; i < array.count; i++) {
// file URL in our bundle
NSURL *fileFromBundle = [[NSBundle mainBundle]URLForResource:[NSString stringWithFormat:#"%#",[array objectAtIndex:i]] withExtension:#"jpg"];
// Destination URL
NSString *path = [self MyImagesDocumentsDirectoryPath];
NSString *filePath = [NSString stringWithFormat:#"%#/%#.jpg",path,[array objectAtIndex:i]];
NSURL *destinationURL = [NSURL fileURLWithPath:filePath];
NSError *error;
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
// copy it over
[[NSFileManager defaultManager]copyItemAtURL:fileFromBundle toURL:destinationURL error:&error];
NSLog(#"%#",error);
}
}
- (NSString *)MyImagesDocumentsDirectoryPath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"/MyFolder"];
return dataPath;
}
here i am copying the images into MyFolder from Main bundle. you can give your zip files name and use this code.

Get File from Directory into NSData

I try to get my file in my self created Directory in the Documents Directory into a NSData Object like this:
NSString *path = [documentsDirectory stringByAppendingFormat:#"%#%#",#"/",fileName];
NSError* errorr = nil;
NSData *fileData = [NSData dataWithContentsOfFile:path options: 0 error: &errorr];
if (fileData == nil)
{
NSLog(#"Failed to read file, error %#", errorr);
}
else
{
}
But i always get this error:
Failed to read file, error Error Domain=NSCocoaErrorDomain Code=257 "The operation couldn’t be completed. (Cocoa error 257.)" UserInfo=0x156be110 {NSFilePath=/var/mobile/Applications/679253E3-652C-45EE-B589-609E52E4E3B0/Documents/upload/test.xml, NSUnderlyingError=0x156ba7f0 "The operation couldn’t be completed. Permission denied"}
So if i check if the file is readable:
if ([[NSFileManager defaultManager] isReadableFileAtPath: path] == YES)
NSLog (#"File is readable");
else
NSLog (#"File is read only");
i get the result that the file is readable, so why do i get the error if i want to parse that file into NSData?!
UPDATE: i created my file like this:
NSString *filePath = [self dataFilePath:fileName];
[xmlData writeToFile:filePath atomically:YES];
- (NSString *)dataFilePath: (NSString *) path {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"upload"];
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:documentsDirectory])
[[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory withIntermediateDirectories:NO attributes:nil error:&error];
NSString *documentsPath = [documentsDirectory
stringByAppendingPathComponent:path];
return documentsPath;
}
UPDATE2: After creating the file, i move it into another Directory with this function:
- (void)moveXmlFilesToUploadDirectory
{
#try {
//Check if FILES_DIR exists
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:FILES_DIR];//filesDir
NSString *uploadDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:UPLOAD_DIR];//filesDir
if ([[NSFileManager defaultManager] fileExistsAtPath:documentsDirectory])
{
NSString *extension = #"xml";
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:NULL];
NSEnumerator *e = [contents objectEnumerator];
NSString *filename;
while ((filename = [e nextObject])) {
if ([[filename pathExtension] isEqualToString:extension]) {
[[NSFileManager defaultManager] moveItemAtPath:documentsDirectory toPath:[uploadDirectory stringByAppendingPathComponent:filename] error:NULL];
}
}
}
}
#catch (NSException *exception) {
}
#finally {
}
}
Maybe the Problem is after moving the file! Cause if i try to get my file into a NSData before i move it, everything works...
It seems that you try to copy the whole directory to a destination meant to be a file. The result is that the filepath is a directory path in the end so you can't open it like a file which leads to the permission error message.
You should update your copy code to
while ((filename = [e nextObject])) {
if ([[filename pathExtension] isEqualToString:extension]) {
[[NSFileManager defaultManager] moveItemAtPath:[documentsDirectory stringByAppendingPathComponent: filename] toPath:[uploadDirectory stringByAppendingPathComponent:filename] error:NULL];
}
}
to copy every file individually. That will create than the actual file at the destination path intend of a directory.
The chances are high that you don't have the right permissions for that file. Please check the permissions and add read access for the current user or "everyone". You can set the read permissions for your user by the info dialog (cmd + i) or in the terminal with chmod u+r test.xml. Eventually you have to set the owner before with
sudo chown yourusername test.xml
Hope that makes sense.

Create directory programmatically

I want to create a directory inside my applicationSupportDirectory. My understanding is that the applicationSupportDirectory does not allow users to see the data within. This is why I have chosen it. However, the code I am using below seems to fail and I am not sure why.
Can anyone tell me what I have done wrong? Thanks!
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *applicationDirectory = [paths objectAtIndex:0]; // Get directory
NSString *dataPath = [applicationDirectory stringByAppendingPathComponent:#"drawings"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
NSError* error;
if([[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error])
;// success
else
{
NSLog(#"Failed");
}
}
}
Try this one, it works for me.
NSString* documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES)[0];
NSString *folder = [documentsPath stringByAppendingPathComponent:#"foldername"];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
if (![fileManager fileExistsAtPath:folder]){
[fileManager createDirectoryAtPath:folder
withIntermediateDirectories:YES
attributes:nil
error:&error];
}
NSString *directoryName = #"drawing";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *applicationDirectory = [paths objectAtIndex:0];
NSString *filePathAndDirectory = [applicationDirectory stringByAppendingPathComponent:directoryName];
NSError *error;
if (![[NSFileManager defaultManager] createDirectoryAtPath:filePathAndDirectory
withIntermediateDirectories:YES
attributes:nil
error:&error])
{
NSLog(#"Create directory error: %#", error);
}
Hope it will help you
To create Dirtectory
NSError *error;
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:#"Library/Application Support/directoryname"];
NSLog(#"%#",path);
if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error];
// Set do not backup attribute to whole folder
}

How to get the list of directores in NSDocumentDirectory?

I have created some directories in NSDocumentDirectory as
if (![tbxCreateFolder.text isEqualToString:#""]) {
NSArray *arrPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryStr = [arrPaths objectAtIndex:0]; // Get documents folder
NSString *dataPath = [documentsDirectoryStr stringByAppendingPathComponent:[NSString stringWithFormat:#"/%#",tbxCreateFolder.text]];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
NSError* error;
if([[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]){
NSLog(#"success");
//Perfrom DB Insertation
}
else
{
NSLog(#"[%#] ERROR: attempting to write create MyFolder directory", [self class]);
NSAssert( FALSE, #"Failed to create directory maybe out of disk space?");
}
}
}
Now i want to get the list of directories that i have created in document folder but response is
NSArray *arrPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePathString = ([arrPaths count] > 0) ? [arrPaths objectAtIndex:0] : nil;
NSLog(#"dirContents %#",basePathString);
Response is:
/Users/amir/Library/Application Support/iPhone Simulator/6.1/Applications/7003E8D5-CCBB-4E54-896B-F4BD2F4D2CB1/Documents
Here is the code:
NSString *documentDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
// create directory named "test"
[[NSFileManager defaultManager] createDirectoryAtPath:[documentDirPath stringByAppendingPathComponent:#"test"] withIntermediateDirectories:YES attributes:nil error:nil];
// retrieved all directories
NSLog(#"%#", [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirPath error:nil]);
NSArray *paths = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentDirPath error:nil];
BOOL isDir = NO;
for (NSString *path in paths) {
if ([fileManager fileExistsAtPath:path isDirectory:&isDir] && isDir) {
// path is directory
}
}
You could always enumerate the contents of the top level directory using -fileExistsAtPath:isDirectory: like this:
NSFileManager *sharedFileManager = [NSFileManager defaultManager];
NSDirectoryEnumerator *files = [sharedFileManager enumeratorAtPath:yourPath];
for (NSString *path in files) {
BOOL isDirectory = NO;
[sharedFileManager fileExistsAtPath:path isDirectory:&isDirectory];
if (isDirectory) {
// you found a directory, so do what you will with it
}
}
You can do this with few simple lines of code
NSString *documentDirectoryPath = // Initialize with Documents path
BOOL isDir = NO;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *files = [fileManager contentsOfDirectoryAtPath:documentDirectoryPath error:NULL];
NSMutableArray *directoriesPaths = [NSMutableArray array];
for (NSString *filePath in files) {
if ([fileManager fileExistsAtPath:filePath isDirectory:&isDir] && isDir) {
[directoriesPaths addObject:filePath];
}
}
NSLog(#"directories %#", directoriesPaths);
try this,
NSArray *arrPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *strFilePath = [[arrPath objectAtIndex:0]
[[NSFileManager defaultManager] createDirectoryAtPath:[strFilePath stringByAppendingPathComponent:#"Sample"] withIntermediateDirectories:YES attributes:nil error:nil];

NSFileManager doesn't create folder

- (NSURL *) applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
....
NSURL *folder = [[[Database sharedInstance] applicationDocumentsDirectory] URLByAppendingPathComponent:#"temp"];
BOOL isFolder;
NSLog(#"URL: %#", folder);
if ([[NSFileManager defaultManager] fileExistsAtPath:folder.absoluteString isDirectory:&isFolder] == NO)
{
NSLog(#"IsFolder: %d", isFolder);
[[NSFileManager defaultManager] createDirectoryAtURL:folder withIntermediateDirectories:YES attributes:nil error:&error];
if (error)
NSLog(#"Error: %#", error.localizedDescription);
}
I run this part of code twice.
I expect that the folder will be created, but every time I receive a log: "IsFolder: 7".
Why the folder wasn't created after the first run?
The problem was in folder.absoluteString.
It should be folder.path instead.
Please, replace folder.absoluteString to folder, your problem will be solved.
Follow step by step:
1) Get documents folder
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
2) Get documents folder and folder name
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:#"MyFolder"];
3) Check alerdy exists or not
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
NSError* error;
if( [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error])
else
{
NSLog(#"[%#] ERROR: attempting to write create MyFolder directory", [self class]);
NSAssert( FALSE, #"Failed to create directory maybe out of disk space?");
}

Resources