I’m able to drag a file URL from a NSTableView cell and drop it in any text editor. According to my understanding of Apple’s documentation though, when I drop the URL, the file should be copied to the drop location.
- (BOOL)tableView:(NSTableView *)tv writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard*)pboard {
//for now putting specific file path in just to get it working
NSString *filePath = @"/Users/Jackh/Desktop/Apple.png";
[pboard declareTypes:[NSArray arrayWithObject:NSURLPboardType] owner:self];
[[NSURL URLWithString:filePath] writeToPasteboard:pboard];
return YES;
}
How do I get the file to copy from the filePath to the dropped location? It’s just moving filePath as text for now.
Any ideas?
Edit: I am now using this code
-(void)awakeFromNib {
[self.tableView setDraggingSourceOperationMask:NSDragOperationEvery forLocal:NO];
}
…
[self.tableView registerForDraggedTypes:[NSArray arrayWithObjects:NSFilenamesPboardType, NSFileContentsPboardType, nil]];
…
- (BOOL)tableView:(NSTableView *)tv writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard*)pboard {
//for now putting specific file path in just to get it working
NSString *filePath = @"/Users/Jackh/Desktop/Apple.png";
[pboard declareTypes:[NSArray arrayWithObject:NSFileContentsPboardType] owner:nil];
[pboard writeFileContents:filePath];
}
If you want to force the green “+” to copy, just use
NSDragOperationCopy(only) in the operation mask, disallowing other operations; e.g. inawakeFromNib:Here is the best way I could find to make your example work with the Finder:
Note that Apple recommends using more modern APIs but I have found in cases like this they have a big side effect: they seem to cause files to be copied twice because URLs are magically copied in multiple forms. Having said that, your original URL example didn’t work because you should have used
writeObjects:on the pasteboard instead of asking the URL towriteToPasteboard:. An example with URLs:As I noted in other comments, if your drag is targeting a document instead of a file manager such as the Finder then it’s better to include the actual data for the file. Raw data can’t be misinterpreted by a document (i.e. the document has to insert the data directly, it can’t choose to insert a path string instead). On the other hand, raw-data drags don’t create files in the Finder for some reason so they’re useful mainly as something to add to the pasteboard as an alternative.
Here is a way to use a UTI to declare the file type and call
NSDatato read a file (I tried this and it works, e.g. I can drag a table view row into a Rich Text document in TextEdit and see an image inserted into the window):(I don’t know exactly why your
writeFileContents:doesn’t work but the above does work and is basically the same thing.)