Question

I have rich-text file with a few images and text. In my Cocoa app I'm trying to put the contents of that file on the NSDragPboard so that the user can drag the contents into other applications (TextEdit, Mail, etc.).

One usecase is this: the rich-text file contains an email template and the user drags the contents into a new Mail message.

I tried this without success:

NSPasteboard *pboard = [NSPasteboard pasteboardWithName:NSDragPboard];
[pboard writeFileContents:filePath];

The Apple docs say this:

Writes the contents of the file filename to the receiver and declares the data to be of type NSFileContentsPboardType and also of a type appropriate for the file’s extension (as returned by the NSCreateFileContentsPboardType function when passed the files extension), if it has one.

In the ClipboardViewer app I can see a few data types, one being NXFileContentsPboardType. However, apps such as Mail and TextEdit don't allow to drop that data type.

When I copy the rich-text content to the clipboard by hand (Control+C), I see all the different data types I want:

  • public.rtf
  • public.utf8-plain-text
  • NSStringPboardType
  • ...

So how can I do that programmatically myself? Do I have to figure out all the various UTI types and set the according data? I thought that's what [pboard writeFileContents:path] was for...

Thanks, Mark.

EDIT:

Making progress... This works for .rtf files, but not for .txt files:

NSString *uti = // helper code to get UTI from NSURL resource key...
NSPasteboard *pboard = [NSPasteboard pasteboardWithName:NSDragPboard];
[pboard declareTypes:[NSArray arrayWithObject:uti] owner:nil];
[pboard setData:[NSData dataWithContentsOfFile:filePath] forType:uti];

For .txt files the data type on the pasteboard is public.text. However, TextEdit and Mail.app won't allow dropping that type. public.rtf in case of rich text works fine...

Was it helpful?

Solution

Looks like it's not possible to add file contents to the pasteboard and have the content types be detected automatically.

It turns out that putting RTF/RTFD file contents on the pasteboard is as simple as:

NSAttributedString *contents = [[NSAttributedString alloc] initWithPath:filePath documentAttributes:NULL];
// This sets the correct type automatically:
[pboard writeObjects:[NSArray arrayWithObject:contents]];
[contents release];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top