移动文件并覆盖

54 *_* 6D 5 file nsfilemanager ios swift

即使已经存在具有相同名称的文件,我也试图移动文件.

NSFileManager().moveItemAtURL(location1, toURL: location2)
Run Code Online (Sandbox Code Playgroud)

这种NSFileManager方法moveItemAtURL有覆盖选项吗?如何替换现有文件?

Chr*_*lla 9

您始终可以检查文件是否存在于目标位置.如果是,请删除它并移动您的项目.

斯威夫特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
  {

  }
}
Run Code Online (Sandbox Code Playgroud)

Swift 3+

try? FileManager.default.removeItem(at: location2)
try FileManager.default.copyItem(at: location1, to: location2)
Run Code Online (Sandbox Code Playgroud)