Search code examples
iosobjective-cnsfilemanager

iPhone copy file


I create two file paths with this code:

NSString *fileName = [[self genRandStringLength:15] stringByAppendingString:@".mp4"];
NSString *finalFilePath = [self.videoFiles stringByAppendingString:fileName];

NSString *tmpFile = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"temp.mp4"]];
[[NSFileManager defaultManager] removeItemAtPath:tmpFile error:NULL];

Then i have some code to create video file and the i want to save it in the Document Folder:

[[NSFileManager defaultManager] copyItemAtPath:tmpFile toPath:finalFilePath error:&err];

And i get this error:

Error Domain=NSCocoaErrorDomain Code=4 "The file “temp.mp4” doesn’t exist." 
UserInfo={NSSourceFilePathErrorKey=/private/var/mobile/Containers/Data/Application/E5B7BBCB-311F-41A3-949D-8A309F535C95/tmp/temp.mp4, NSUserStringVariant=(
    Copy
    ), NSDestinationFilePath=/var/mobile/Containers/Data/Application/E5B7BBCB-311F-41A3-949D-8A309F535C95/Documents/VideoFiles/0iWDmhLvbbzM6SE.mp4, NSFilePath=/private/var/mobile/Containers/Data/Application/E5B7BBCB-311F-41A3-949D-8A309F535C95/tmp/temp.mp4, NSUnderlyingError=0x12f0099b0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

Any idea what can be the problem?

Just for some checking i try to copy the video to the iPhone Photo library with : UISaveVideoAtPathToSavedPhotosAlbum(tmpFile, self, nil, nil);

And it's work fine, so the file is exist.


Solution

  • Use this code

    NSString *fileName = [[self genRandStringLength:15] stringByAppendingString:@".mp4"];
    NSString *finalFilePath = [self.videoFiles stringByAppendingString:fileName];
    
    NSString *tmpFile = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"temp.mp4"]];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL success = [fileManager fileExistsAtPath:tmpFile];
    
    if (success)
    {
      [[NSFileManager defaultManager] copyItemAtPath:tmpFile toPath:finalFilePath error:&err];
    
      [[NSFileManager defaultManager] removeItemAtPath:tmpFile error:NULL];
    
    }