How can I accept Directories in a Drag and Drop zone?

272 Views Asked by At

Hello I've implemented multiple drag and drop areas in my app and by now everything worked fine because I only had to drop files of various types.

Now I have a NSView where I need to drop only folders. I took the code from a tutorial where it explain how to filter types, but I can't figure out how to add folders to the accepted types.


//MARK: - DROP AREA CLASS

// Invisible area needed to drop files
class FolderDropArea: NSView {

    let viewModel = ViewModel()

    // declare the supported files that can be dropped in
    let supportedTypes: [NSPasteboard.PasteboardType] = [ .fileURL, .sound, ]

    let fileManager = FileManager.default

    override func awakeFromNib() {
        super.awakeFromNib()

        //registerd to be a drag zone
        self.registerForDraggedTypes(supportedTypes)

        // Enable layer in self view.
        self.wantsLayer = true

        self.layer?.cornerRadius = 0.0
        self.layer?.borderWidth = 1.0
        self.layer?.borderColor = CGColor(red: 0, green: 0, blue: 0, alpha: 0)

    }

    //MARK: - DRAG IN OPERATIONS

    // detects the if the type dragged is accepted
    override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {

        let canReadPasteboardObjects = sender.draggingPasteboard.canReadObject(forClasses: [NSImage.self, NSColor.self, NSString.self, NSURL.self, NSSound.self], options: acceptableUTITypes())

        print("Draggin entered")

        if canReadPasteboardObjects {
            highlight()
            return .copy
        }

        return NSDragOperation()
    }

    //MARK: - Operaiton at drop
    override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
        guard let pasteboardObjects = sender.draggingPasteboard.readObjects(forClasses: [NSImage.self, NSColor.self, NSString.self, NSURL.self,  NSSound.self], options: acceptableUTITypes()), pasteboardObjects.count > 0 else {
            return false
        }

        pasteboardObjects.forEach { (object) in
            if let url = object as? NSURL {
                self.handleFileURLObject(url as URL)
            }
        }
        return true
    }

    func acceptableUTITypes() -> [NSPasteboard.ReadingOptionKey : Any] {
        let types = [NSImage.imageTypes, NSString.readableTypeIdentifiersForItemProvider, NSSound.soundUnfilteredTypes].flatMap { $0 }
        return [NSPasteboard.ReadingOptionKey.urlReadingContentsConformToTypes : types]
    }
}

I removed all the useless code and I just left how I declare the accepted types. I don't have a clue how to accept folders.

EDIT: when I move a folder in the area, the console prints "dragging entered" because it is a fileUrl type, but it doesn't call the highlight func, therefore it's not considered a readable object

0

There are 0 best solutions below