7

I'm trying to move a file even if a file with the same name already exists.

NSFileManager().moveItemAtURL(location1, toURL: location2)

Does NSFileManager's method moveItemAtURL have an override option? How can I replace the existing file?

54 69 6D
  • 664
  • 7
  • 17
  • Delete the destination file and then do the move. – EmilioPelaez Mar 29 '16 at 21:39
  • 1
    theres a lot of objc answers to this question. you might be able to convert some of those answers to swift, such as http://stackoverflow.com/questions/6137423/how-to-overwrite-a-file-with-nsfilemanager-when-copying and http://stackoverflow.com/questions/20683696/how-to-overwrite-a-folder-using-nsfilemanager-defaultmanager-when-copying – Will M. Mar 29 '16 at 21:40

1 Answers1

14

You can always check if the file exists in the target location. if it does, delete it and move your item.

Swift 2.3

let filemgr = NSFileManager.defaultManager()

if !filemgr.fileExistsAtPath(location2) 
{
  do
  {
    try filemgr.moveItemAtURL(location1, toURL: location2)
  }
  catch
  {
  }
}
else
{
  do
  {
    try filemgr.removeItemAtPath(location2)
    try filemgr.moveItemAtURL(location1, toURL: location2)
  }
  catch
  {

  }
}

Swift 3+

try? FileManager.default.removeItem(at: location2)
try FileManager.default.copyItem(at: location1, to: location2)
Christian Abella
  • 5,439
  • 2
  • 26
  • 39
  • would this not be more concise: `if filemgr.fileExistsAtPath(location2) { do { try filemgr.removeItemAtPath(location2) } catch { } } do { try filemgr.moveItemAtURL(location1, toURL: location2) } catch { }` – chriswillow Jan 09 '18 at 08:23
  • For 'Swift 3 and above', you may check the answer here https://stackoverflow.com/a/49854283/2641380 as we can not answer it here. – SHS Apr 16 '18 at 09:52