MacOS: 13.0 (22A380)
swift:
import Cocoa
private func copyToClipBoard() {
let pasteboard = NSPasteboard.general
var emptyArray = [NSURL]()
emptyArray.append(NSURL(fileURLWithPath: "/some-file-exist/test"))
pasteboard.clearContents()
pasteboard.writeObjects(emptyArray)
}
copyToClipBoard()
ObiectiveC:
int main(int argc, const char * argv[]) {
PasteboardRef clipboard;
if (PasteboardCreate(kPasteboardClipboard, &clipboard) != noErr) {
return -1;
}
if (PasteboardClear(clipboard) != noErr) {
return -1;
}
// if (PasteboardSynchronize(clipboard) != noErr) {
// return -1;
// }
NSURL *url = [NSURL fileURLWithPath:@"/some-file-exist/test"];
PasteboardItemID itemID = (__bridge void *)url;
CFDataRef utf8Data = (__bridge CFDataRef)[[url absoluteString] dataUsingEncoding:NSUTF8StringEncoding];
PasteboardPutItemFlavor(clipboard, itemID, kUTTypeFileURL, utf8Data, kPasteboardFlavorNoFlags);
ItemCount itemCount;
PasteboardGetItemCount(clipboard, &itemCount);
printf("%ld\n", itemCount);
CFRelease(clipboard);
CFRelease(utf8Data);
return 0;
}
I try simulate finder copy file action, but so far, I just let item visible in the clipboard, copy action working fine in Finder application, But other application cannot read clipboard file item or use it.
I already search a lot of information, and after comparing, I found that Keyboard Maestro have a function : Set System Clipboard to File Reference, it works just fine.
So, I believe, there must be some way to meet my needs, please help me!

Given a file URL to the file (eg
[NSURL fileURLWithPath:thePath]), you can write the flavor kUTTypeFileURL with value the UTF8 string encoding of the URL (eg[url.absoluteString dataUsingEncoding:NSUTF8StringEncoding]), for example usingPasteboardPutItemFlavor.As to how you do that with Swift, I have no idea. But that is how Keyboard Maestro writes file references to the clipboard.