Skip to content

Instantly share code, notes, and snippets.

@sketchytech
Last active May 5, 2022 22:33
Show Gist options
  • Save sketchytech/c81e0e37edabca06600960c46c0a0736 to your computer and use it in GitHub Desktop.
Save sketchytech/c81e0e37edabca06600960c46c0a0736 to your computer and use it in GitHub Desktop.
FileManager: Replace with copy of file
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