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及以上版本”,你可以在这里检查答案,因为我们不能在这里回答。