Search code examples
swiftmacosnstableviewnsoutlineviewnspasteboard

How can I drag a folder/directory item from an NSOutlineView to an app like Finder or Xcode


I've created an outline view table that shows my disk (file system) hierarchy similar to this example from Apple :

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/OutlineView/Articles/UsingOutlineDataSource.html#//apple_ref/doc/uid/20000725-142693

Now I want to be able to drag files/folders from my outline view to other applications that accept drops like Finder, Xcode, iTunes etc. These are the functions that I'm implementing for my data source for NSOu

let pb: NSPasteboard?
func outlineView(outlineView: NSOutlineView, writeItems items: [AnyObject], toPasteboard pasteboard: NSPasteboard) -> Bool {
    var array = [NSURL]()
    self.pb?.declareTypes([NSFilesPromisePboardType], owner: self)
    if let fileItem = items[0] as? FileSystemItem {
        let fileURL = NSURL(fileURLWithPath: fileItem.getFullPath()!)
        array.append(fileURL)
        self.pb?.addTypes([fileURL.pathExtension!], owner: nil)
        self.pb?.writeObjects(array)
        return true
    }else {
        return false
    }
}
func outlineView(outlineView: NSOutlineView, namesOfPromisedFilesDroppedAtDestination dropDestination: NSURL, forDraggedItems items: [AnyObject]) -> [String] {
    var names = [String]()
    if let fileItem = items[0] as? FileSystemItem {
        print(fileItem.getRelativePath())
        names.append(fileItem.getRelativePath()!)
        return names
    }else {
        return names
    }
}

I'm currently getting this error in the console

Looked for HFSPromises on the pasteboard, but found none.

Finally this is a screenshot of what I have - NSOutlineView showing file system


Solution

  • Don't use promises unless the file does not exist and you will create it at a location specified by the recipient. If it is a single file, use NSURLPboardType. For multiple files, use NSFilenamesPboardType.