3
votes

I'm trying to copy a temp file to another location using NSFileManager. However it's failing and complaining that one of the files does not exists.

 //Copy temp file
    NSError *error;
    BOOL exists = [fileManager fileExistsAtPath:chapterFileTemp];
    exists = [fileManager fileExistsAtPath:chapterFile];

    [fileManager copyItemAtURL:[NSURL fileURLWithPath:chapterFileTemp]
                         toURL:[NSURL fileURLWithPath:chapterFile]
                         error:&error];

    //Delete temp path
    [fileManager removeItemAtURL:[NSURL fileURLWithPath:chapterFileTemp] error:&error];

I'm getting error at copy operation

(Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be completed. (Cocoa error 260.)" UserInfo=0x1c5190b0 {NSFilePath=/var/mobile/Applications/57727CCD-88AD-4D84-8C78-EA8100645C9B/Documents/119/myFileTemp.temp, NSUnderlyingError=0x1c527960 "The operation couldn’t be completed. No such file or directory").

Now the first BOOL returns YES, and the second one NO. Which is expected.

What could be the reason for failure

Thanks.

2
Note: why create the NSURL? Just use copyItemAtPath:toPath:error.GoZoner
Yes, initially I had the code in that way... but same error.Pablo

2 Answers

3
votes

This is possible when the destination path is missing the directory. Make sure that the place at which you want to copy the source file is containing all required directory.

2
votes

If, as +Apurv noted, the target directory doesn't exist, then you should do two things:

  1. Ensure that your target location, chapterFile, is created in a location that you have access to. iOS Apps are restricted in where they can write files; you need to create a path that is consistent with the iOS App restrictions. See URLsForDirectory:inDomains.
  2. Invoke createDirectoryAtPath:withIntermediateDirectories:attributes:error: to create the target directory.

After these two things, the copyItem method should work.

Use, from NSFileManager

- (BOOL)createDirectoryAtPath:(NSString *)path
  withIntermediateDirectories:(BOOL)createIntermediates
                   attributes:(NSDictionary *)attributes
                        error:(NSError **)error

with createIntermediates as YES.