Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move file and override [duplicate]

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?

like image 670
54 69 6D Avatar asked Mar 29 '16 21:03

54 69 6D


1 Answers

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)
like image 180
Christian Abella Avatar answered Oct 23 '22 06:10

Christian Abella