0

I'm looking to perform copy/paste operations with Swift with audio clips on MacOS. This can be done using Finder by right clicking on an audio clip, selecting copy, and then pasting it.

Currently, when an audio file is copied, it is sent to the default system-wide clipboard, which can be accessed through Finder > Edit > Show Clipboard. When viewing the clipboard, I see the title of the audio file (not path) in the main clipboard field, and a footer displaying "Clipboard contents: text / items" at the bottom.

I want to replicate this behaviour with Swift, so I figure that I should use the NSPasteboard.general instance, as it would allow me to modify the contents of the clipboard.

This is what I have so far when it comes to copying an item to the clipboard:

let pasteboard = NSPasteboard.general
pasteboard.clearContents()
pasteboard.setString(audioPath.absoluteString, forType: .URL)

However, this results in an empty main clipboard field, and a footer that displays "Clipboard contents: unknown".

I also tried doing:

let audio = try Data(contentsOf: path)
let pasteboard = NSPasteboard.general
pasteboard.clearContents()
pasteboard.setData(audio, forType: .sound)

But the clipboard would display the same message.

How could I programmatically recreate Finder's copy/pasting ability using Swift?

  • 1
    [`NSPasteBoard#writeFileContents(_:)`](https://developer.apple.com/documentation/appkit/nspasteboard/1531224-writefilecontents)? – MadProgrammer Apr 24 '20 at 21:54
  • Says in the [NSPasteboard Documentation](https://developer.apple.com/documentation/appkit/nspasteboard) that this function is intended for macOS 10.5 and earlier (I'm running MacOS v10.14.6). Despite this, I tried passing in both the absolute path of the file and then just the name of the file into the writeFileContents function but still nothing changes in the clipboard. – Maxim Kuzmenko Apr 24 '20 at 22:13
  • Does this answer your question? [How to use NSPasteboard with kPasteboardTypeFileURLPromise for copy/paste?](https://stackoverflow.com/questions/58886232/how-to-use-nspasteboard-with-kpasteboardtypefileurlpromise-for-copy-paste) – Willeke Apr 25 '20 at 08:18
  • @Willeke Getting closer; files promises definitely seems to be the mechanism through which finder file copy/pasting can happen, although unfortunately it seems to only be supported for drag-and-drop, not for copying and pasting. – Maxim Kuzmenko May 01 '20 at 04:13

0 Answers0