Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 移动文件并覆盖_Ios_Swift_File_Nsfilemanager - Fatal编程技术网

Ios 移动文件并覆盖

Ios 移动文件并覆盖,ios,swift,file,nsfilemanager,Ios,Swift,File,Nsfilemanager,我正在尝试移动文件,即使已经存在同名文件 NSFileManager().moveItemAtURL(location1, toURL: location2) NSFileManager的方法moveItemAttribute是否具有覆盖选项?如何替换现有文件?您可以随时检查目标位置是否存在该文件。 如果有,请删除它并移动您的项目 Swift 2.3 let filemgr = NSFileManager.defaultManager() if !filemgr.fileExistsAtPa

我正在尝试移动文件,即使已经存在同名文件

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

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

您可以随时检查目标位置是否存在该文件。 如果有,请删除它并移动您的项目

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)

删除目标文件,然后移动。这个问题有很多objc答案。您可能能够将其中一些答案转换为swift,例如,这不是更简洁吗:
如果filemgr.fileExistsAtPath(location2){do{try filemgr.removitematpath(location2)}catch{}}do{try filemgr.moveitematrol(location1,toURL:location2)}catch{}
表示“swift 3及以上版本”,你可以在这里检查答案,因为我们不能在这里回答。