iosmacosclipboardnspasteboard

Disable Universal Clipboard temporarily


iOS and macOS have a built in feature called Universal Clipboard that syncs the clipboard's content across devices using iCloud.

NSPasteboard.general.clearContents()
NSPasteboard.general.writeObjects("Test 123") 

I would like to write something to the general pasteboard on my Cocoa app to share it across apps without it being synced with other iCloud devices. I wasn't able to find a way to do it. In fact I think it is not possible without the user disabling it manually in the settings.

The docs say:

The general pasteboard, available by way of the general class method, automatically participates with the Universal Clipboard feature in macOS 10.12 and later and in iOS 10.0 and later. There is no macOS API for interacting with this feature. https://developer.apple.com/documentation/appkit/nspasteboard

But maybe there is a workaround, a private API (no App Store, I know) or something else someone might know about. :)

Cheers


Solution

  • Yes, the general pasteboard is available to all apps, but the NSPasteboard can be used to create private pasteboards. All you need to do is:

    let myPasteboard = NSPasteboard(name: NSPasteboard.Name("mypasteboard"))
    

    You can check the documentation here. Thus, you can copy the pasted item to your private pasteboard and, only when you want it, you can then transfer the data to the general pasteboard and make the data available to all apps.

    However, if you want to prevent the Universal Clipboard from being shared across devices, all you have to do is:

    let generalPasteboard = NSPasteboard.general
    
    // current host only
    generalPasteboard.prepareForNewContents(with: .currentHostOnly)
    // write here to the pasteboard