I ended up getting a response via the Cocoa-dev mailing list. Basically, you need to attach an NSURL
directly linking to the file. It doesn't work for external images, and NSImage
is never used:
NSString *fileUrl = @"http://i.imgur.com/V8w9fKt.gif";
NSString *fileName = [fileUrl lastPathComponent];
NSURL *saveUrl = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@", NSTemporaryDirectory()]];
saveUrl = [saveUrl URLByAppendingPathComponent:fileName];
// Write image to temporary directory
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileUrl]];
[data writeToURL:saveUrl atomically:YES];
// Attach the raw NSURL pointing to the local file
NSArray *shareItems = [NSArray arrayWithObjects:saveUrl, @"Text", nil];
// Open share prompt
NSSharingService *service = [NSSharingService sharingServiceNamed:NSSharingServiceNameComposeMessage];
service.delegate = self;
[service performWithItems:shareItems];
I then implemented didShareItems and didFailToShareItems so that I could remove the file after sharing was complete:
- (void)sharingService:(NSSharingService *)sharingService didShareItems:(NSArray *)items{
NSString *path = items[0];
[self removeFile:path];
}
...
- (void)removeFile:(NSString *)path{
[[NSFileManager defaultManager] removeItemAtPath:path error:NULL];
}
And for those struggling, I found the following method was required for everything to work properly:
- (NSWindow *)sharingService:(NSSharingService *)sharingService sourceWindowForShareItems:(NSArray *)items sharingContentScope:(NSSharingContentScope *)sharingContentScope{
return self.window;
}
I realize some of that code is improper (my URLWithString
creation is counterintuitive, but I'm learning), but this should get those struggling a starting point.