Swift - MacOS NSPasteboard - simultaneously support HTML and plain strings

269 views Asked by At

I have a use-case where I want my application to store clipboard data and later allow the user to paste it out.
The thing is - I want to both support HTML-styled text (while maintaining its styling) and also support simple plain-text.
What I have so far is:
  • Pasteboard variable setup
let pasteboard = NSPasteboard.general
pasteboard.declareTypes([.html, .string], owner: nil)
  • Storing user's clipboard data
let copiedString = pasteboard.string(forType: .html) ?? pasteboard.string(forType: .string) {
    If, for example, a user copies text from the browser, this method maintains the entire HTML.
    Alternatively, if text is being copied from applications that don't support HTML (such as XCode, Notes, etc), `copiedString` will simply hold the plain text.
  • Later down the line - pushing contents back to clipboard
pasteboard.setString(copiedString, forType: .html)

My problem is, when I try to paste the content pushed into my clipboard; it only works in applications that actually support HTML-formatted text, such as Chrome / Microsoft Word.
When I try to paste the content into XCode for example, it simply doesn't spit out anything.

Ideally, I want my clipboard to adjust itself according to the application I'm on - paste the text as HTML if supported by the application, otherwise - paste the plain text.

How can I implement such behavior?
Thanks!

0

There are 0 answers