移动文件并覆盖

时间:2016-03-29 21:37:01

标签: ios swift file nsfilemanager

即使已经存在同名文件,我也试图移动文件。

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

NSFileManager方法moveItemAtURL是否有覆盖选项?如何替换现有文件?

1 个答案:

答案 0 :(得分:9)

您始终可以检查目标位置中是否存在该文件。 如果是,请将其删除并移动您的项目。

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)