Add Support for Drag and Drop to SwiftUI-based macOS App
There are 2 types of drag and drop I'm interested in for SimplyDiskSweeper:
- Drag and drop folders onto the app icon in the Dock
- Drag and drop folders onto the app window
It's easy to implement both in SwiftUI.
DRAG AND DROP FOLDERS ONTO THE APP ICON IN THE DOCK
ContentView() .onOpenURL { url in handleDropOnDockAppIcon(url: url) }
If you use XcodeGen, add this to project.yml:
targets:
:
#settings, dependencies, scheme, entitlements etc
info:
path: /Info.plist
properties:
CFBundleDocumentTypes:
- CFBundleTypeRole: Viewer
LSHandlerRank: Default
LSItemContentTypes:
- public.folder
otherwise amend Info.plist accordingly.
DRAG AND DROP FOLDERS ONTO THE APP WINDOW
ContentView() .onDrop(of: ["public.file-url"], isTargeted: nil) { providers -> Bool in providers.first?.loadDataRepresentation(forTypeIdentifier: "public.file-url", completionHandler: { data, _ in if let data = data, let path = String(data: data, encoding: .utf8), let url = URL(string: path as String) { handleDropInWindow(url: url) } }) return true }
Discussion in the ATmosphere