diff --git a/WhatCopiedMac/Modules/Sources/FoundationExtensions/FileManager+Extension.swift b/WhatCopiedMac/Modules/Sources/FoundationExtensions/FileManager+Extension.swift new file mode 100644 index 0000000..7a6625c --- /dev/null +++ b/WhatCopiedMac/Modules/Sources/FoundationExtensions/FileManager+Extension.swift @@ -0,0 +1,16 @@ +// +// FileManager+Extension.swift +// WhatCopied +// +// Created by cyan on 2024/12/11. +// + +import Foundation + +public extension FileManager { + func directoryExists(at url: URL) -> Bool { + var isDirectory: ObjCBool = false + let fileExists = fileExists(atPath: url.path, isDirectory: &isDirectory) + return fileExists && isDirectory.boolValue + } +} diff --git a/WhatCopiedMac/Sources/AppDelegate.swift b/WhatCopiedMac/Sources/AppDelegate.swift index 7d07189..5000153 100644 --- a/WhatCopiedMac/Sources/AppDelegate.swift +++ b/WhatCopiedMac/Sources/AppDelegate.swift @@ -39,6 +39,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate { } } + func applicationWillTerminate(_ notification: Notification) { + try? FileManager.default.removeItem(at: .previewingDirectory) + } + func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { true } diff --git a/WhatCopiedMac/Sources/Controllers/MainVC+Data.swift b/WhatCopiedMac/Sources/Controllers/MainVC+Data.swift index 65cbdb5..175eeb8 100644 --- a/WhatCopiedMac/Sources/Controllers/MainVC+Data.swift +++ b/WhatCopiedMac/Sources/Controllers/MainVC+Data.swift @@ -27,7 +27,7 @@ extension MainVC { } var previewingFileURL: URL { - URL.temporaryDirectory.appendingPathComponent(suggestedFileName) + .previewingDirectory.appendingPathComponent(suggestedFileName) } func reloadTypes() { diff --git a/WhatCopiedMac/Sources/Controllers/MainVC.swift b/WhatCopiedMac/Sources/Controllers/MainVC.swift index 0f66abb..738ce2f 100644 --- a/WhatCopiedMac/Sources/Controllers/MainVC.swift +++ b/WhatCopiedMac/Sources/Controllers/MainVC.swift @@ -70,8 +70,6 @@ final class MainVC: NSViewController { } override func endPreviewPanelControl(_ panel: QLPreviewPanel?) { - Task { @MainActor in - try? FileManager.default.removeItem(at: previewingFileURL) - } + // no-op } } diff --git a/WhatCopiedMac/Sources/Extensions/URL+Extension.swift b/WhatCopiedMac/Sources/Extensions/URL+Extension.swift new file mode 100644 index 0000000..9c7460a --- /dev/null +++ b/WhatCopiedMac/Sources/Extensions/URL+Extension.swift @@ -0,0 +1,25 @@ +// +// URL+Extension.swift +// WhatCopied +// +// Created by cyan on 2024/12/11. +// + +import Foundation + +extension URL { + static var previewingDirectory: URL { + let directory = temporaryDirectory.appendingPathComponent("QuickLook") + let fileManager = FileManager.default + + if !fileManager.directoryExists(at: directory) { + do { + try fileManager.createDirectory(at: directory, withIntermediateDirectories: false) + } catch { + Logger.log(.error, "Failed to create previewing directory: \(error.localizedDescription)") + } + } + + return directory + } +}