I am working on a macOS application that involves creating a folder in a temporary directory.
How can I allow users to drag a folder icon off of the Cocoa app and onto their desktop (or into Finder and other apps) so that dropping it will actually paste the folder created by the app?
I have so far been able to write the finished folder that I want to save to a temporary directory. How do I place a folder icon on the application that can be dragged into the Finder? Thanks!
The complete code I'm currently using is this:
class draggableFolder: NSImageView {
override func mouseDown(with theEvent: NSEvent) {
let pasteboardItem = NSPasteboardItem()
// pasteboardItem.availableType(from: [NSPasteboard.PasteboardType.fileURL])
pasteboardItem.setDataProvider(self, forTypes: [kUTTypeURL as NSPasteboard.PasteboardType])
let draggingItem = NSDraggingItem(pasteboardWriter: pasteboardItem)
draggingItem.setDraggingFrame(self.bounds, contents:self.image)
beginDraggingSession(with: [draggingItem], event: theEvent, source: self as NSDraggingSource)
}
}
extension draggableFolder: NSDraggingSource {
func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {
return NSDragOperation.generic
}
}
extension draggableFolder: NSPasteboardItemDataProvider {
func pasteboard(_ pasteboard: NSPasteboard?, item: NSPasteboardItem, provideDataForType type:
NSPasteboard.PasteboardType) {
print("dataprovider")
if let pasteboard = pasteboard, type.rawValue == String(describing: kUTTypeURL) {
let folder = currentIconsetURL
print("dataprovider2")
print(NSURL.init(fileURLWithPath: currentIconsetURL))
pasteboard.clearContents()
pasteboard.declareTypes([NSPasteboard.PasteboardType.fileNameType(forPathExtension: "appiconset")], owner: nil)
pasteboard.writeObjects([(URL.init(fileURLWithPath: currentIconsetURL).absoluteURL as NSURL) as NSPasteboardWriting])
}
}
}
Sadly, the drag and drop guide Apple has is based entirely on the old deprecated API: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DragandDrop/DragandDrop.html
The rough outline for what you're asking, using the modern API is:
NSDraggingSource
protocol to return that it supports the Copy operation only (draggingSession(_:sourceOperationMaskFor:)
).mouseDown
(with a tracking loop) or mouseDragged
, once the user's drag has moved a certain distance from its original location (3 or 4 points is all), then you should start a dragging session (NSView beginDraggingSession
)NSDraggingItem
where you pass in the URL for the folder (as an NSURL
, not a Swift URL
, because only the former conforms to NSPasteboardWriter
).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With