Move item to trash with file coordinator

This commit is contained in:
1024jp 2024-05-20 15:58:31 +09:00
parent 1b559c22e5
commit 77bba583bd
2 changed files with 29 additions and 1 deletions

View File

@ -236,6 +236,34 @@ import OSLog
}
/// Properly moves the item to the trash.
///
/// - Parameters:
/// - fileURL: The URL of an item to move to trash.
func trashItem(at fileURL: URL) throws {
var trashedURL: NSURL?
var coordinationError: NSError?
var trashError: (any Error)?
NSFileCoordinator(filePresenter: self).coordinate(writingItemAt: fileURL, options: .forDeleting, error: &coordinationError) { newURL in
do {
try FileManager.default.trashItem(at: newURL, resultingItemURL: &trashedURL)
} catch {
trashError = error
}
}
if let error = coordinationError ?? trashError {
throw error
}
guard trashedURL != nil else {
assertionFailure("This guard should success.")
throw CocoaError(.fileWriteUnknown)
}
}
// MARK: Private Methods
/// Changes the frontmost document.

View File

@ -114,7 +114,7 @@ struct FileBrowserView: View {
Button(String(localized: "Move to Trash", table: "Document", comment: "menu item label")) {
do {
try FileManager.default.trashItem(at: node.fileURL, resultingItemURL: nil)
try self.document.trashItem(at: node.fileURL)
AudioServicesPlaySystemSound(.moveToTrash)
} catch {
self.error = error