Last active
May 5, 2022 22:33
-
-
Save sketchytech/c81e0e37edabca06600960c46c0a0736 to your computer and use it in GitHub Desktop.
FileManager: Replace with copy of file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension FileManager { | |
func replaceWithCopyOfFile(at:URL, with:URL) { | |
do { | |
let url = try self.url(for: .itemReplacementDirectory, in: .userDomainMask, appropriateFor: with.deletingPathExtension(), create: true) | |
try self.copyItem(at: with, to: url.appendingPathComponent(with.lastPathComponent)) | |
let alert = NSAlert() | |
alert.messageText = "Replace \"\(at.lastPathComponent)\" in \"\(at.pathComponents[at.pathComponents.count - 2])\" with new file?" | |
alert.addButton(withTitle: "OK") | |
alert.addButton(withTitle: "Cancel") | |
if alert.runModal() == NSAlertFirstButtonReturn { | |
_ = try FileManager.default.replaceItemAt(at, withItemAt: url.appendingPathComponent(with.lastPathComponent)) | |
} | |
// removes whole temporary directory as a clean up | |
try self.removeItem(at: url) | |
} | |
catch { | |
// error | |
print("unknown error") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment