即使已经存在同名文件,我也试图移动文件。
NSFileManager().moveItemAtURL(location1, toURL: location2)
NSFileManager
方法moveItemAtURL
是否有覆盖选项?如何替换现有文件?
答案 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)