I\'m using this method to copy a file:
[fileManager copyItemAtPath:sourcePath toPath:targetPath error:&error];
I want to overwrite a fi
Detect file exists error, delete the destination file and copy again.
Sample code in Swift 2.0:
class MainWindowController: NSFileManagerDelegate {
let fileManager = NSFileManager()
override func windowDidLoad() {
super.windowDidLoad()
fileManager.delegate = self
do {
try fileManager.copyItemAtPath(srcPath, toPath: dstPath)
} catch {
print("File already exists at \'\(srcPath)\':\n\((error as NSError).description)")
}
}
func fileManager(fileManager: NSFileManager, shouldProceedAfterError error: NSError, copyingItemAtPath srcPath: String, toPath dstPath: String) -> Bool {
if error.code == NSFileWriteFileExistsError {
do {
try fileManager.removeItemAtPath(dstPath)
print("Existing file deleted.")
} catch {
print("Failed to delete existing file:\n\((error as NSError).description)")
}
do {
try fileManager.copyItemAtPath(srcPath, toPath: dstPath)
print("File saved.")
} catch {
print("File not saved:\n\((error as NSError).description)")
}
return true
} else {
return false
}
}
}