I\'m using this method to copy a file:
[fileManager copyItemAtPath:sourcePath toPath:targetPath error:&error];
I want to overwrite a fi
I think what you're looking for is the NSFileManagerDelegate protocol method:
- (BOOL)fileManager:(NSFileManager *)fileManager shouldProceedAfterError:(NSError *)error copyingItemAtPath:(NSString *)srcPath toPath:(NSString *)dstPath;
From this method, you can decide what to do with the existing file (rename/delete) and then proceed with the copy.
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
}
}
}
I think the possibility of the nanosecond you mensioned is feeble. so stick to the first method of removing the existing file and copying the new file.
This is for improvement of 'Swift 3 and above' of question 'Move file and override [duplicate]' which is marked duplicate of this question.
To move file from sourcepath(string) to DestinationPath(string). Delete the existing file if same name file already exists at DestinationPath.
// Set the correct path in string in 'let' variables.
let destinationStringPath = ""
let sourceStringPath = ""
let fileManager:FileManager = FileManager.default
do
{
try fileManager.removeItem(atPath: sourceStringPath)
}
catch
{
}
do
{
try fileManager.moveItem(atPath: sourceStringPath, toPath: destinationStringPath)
}
catch
{
}
For overwriting files, I prefer
NSData *imgDta = UIImageJPEGRepresentation(tImg, 1.0);
[imgDta writeToFile:targetPath options:NSDataWritingFileProtectionNone error:&err];
Removing & copying files in loop sometimes doesn't work as intended
Swift4:
_ = try FileManager.default.replaceItemAt(previousItemUrl, withItemAt: currentItemUrl)