Search code examples
iosnsfilemanager

NSFileManager: duplicate file if exists


I'd like to have OSX-behaviour in my iOS-App when copying files: if it exists, append a counter to it:

  • myFile.png => myFile 1.png
  • myFile20.png => myFile20 1.png
  • myFile 20.png => myFile 21.png
  • ...

Is there a built-in way to do this or do I have to build that functionality myself? I couldn't find anything like that but I don't think I'm the first one needing this behaviour...


Solution

  • You can do something like this, where requestedName is the file name the user selected, extension is the extension of the file and basePath is the folder you're trying to store it in:

     NSFileManager *fm = [NSFileManager defaultManager];
     NSString * filename = requestedName;
    
     if ([fm fileExistsAtPath:[basePath stringByAppendingPathComponent:requestedName]]) 
    {   
         unsigned int counter = 1;
         while ( [fm fileExistsAtPath: [basePath stringByAppendingPathComponent: filename]]) 
         {
             //NSLog(@"File already exists %@", filename);
             NSURL *originalFilePath = [NSURL URLWithString:[kTempPath stringByAppendingPathComponent:filename]];
             filename = [[NSString stringWithFormat: @"%@-%d",
             [requestedName stringByDeletingPathExtension], counter]stringByAppendingPathExtension: extension];
             counter ++;
             NSURL *newFilePath = [NSURL URLWithString:[kTempPath stringByAppendingPathComponent:filename]];
             [fm moveItemAtURL:originalFilePath toURL:newFilePath error:nil]; 
          // just in case
             if (counter > 512) break;
         }
    }
    

    if the file doesn't exist then just move it to the correct location using moveItemAtURLor moveItemAtPathfrom the NSFileManager.