Writing a string to NSPasteBoard
Swift 2:
Copy a string to the general pasteboard with Swift 2:
let pasteboard = NSPasteboard.generalPasteboard()
pasteboard.declareTypes([NSPasteboardTypeString], owner: nil)
pasteboard.setString("Hello", forType: NSPasteboardTypeString)
Here is the working version of the method:
- (BOOL) writeToPasteBoard:(NSString *)stringToWrite
{
[pasteBoard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
return [pasteBoard setString:stringToWrite forType:NSStringPboardType];
}
Before you copy a string on NSPasteboard it's better to clear the contents and then save.
Swift 4
// Set string
NSPasteboard.general.clearContents()
NSPasteboard.general.setString("I copied a string", forType: .string)
// Read copied string
NSPasteboard.general.string(forType: .string)
Objective-C
// Set string
[[NSPasteboard generalPasteboard] clearContents];
[[NSPasteboard generalPasteboard] setString:@"I copied a string" forType:NSPasteboardTypeString];
// Read string
[[NSPasteboard generalPasteboard] stringForType:NSPasteboardTypeString];
And also there are other available types for copying items on NSPasteboard. Like:
- NSPasteboardTypeString
- NSPasteboardTypePDF
- NSPasteboardTypeTIFF
- NSPasteboardTypePNG
- NSPasteboardTypeRTF
You can find more details on https://developer.apple.com/documentation/appkit/nspasteboardtype.