Reading from the Clipboard with Swift 3 on MACos

Reading from the clipboard with Swift 3 on macOS

Works for Swift 3 and Swift 4

// Set string to clipboard
let pasteboard = NSPasteboard.general
pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
pasteboard.setString("Good Morning", forType: NSPasteboard.PasteboardType.string)

var clipboardItems: [String] = []
for element in pasteboard.pasteboardItems! {
if let str = element.string(forType: NSPasteboard.PasteboardType(rawValue: "public.utf8-plain-text")) {
clipboardItems.append(str)
}
}

// Access the item in the clipboard
let firstClipboardItem = clipboardItems[0] // Good Morning

Swift 3 copy string to clipboard

Swift 3 you copy it like this way.

 let pasteboard = NSPasteboard.general()
pasteboard.declareTypes([NSPasteboardTypeString], owner: nil)
pasteboard.setString("Good Morning", forType: NSPasteboardTypeString)

Get path of file from clipboard in OS X

Try this:

NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
NSArray *classes = [NSArray arrayWithObject:[NSURL class]];

NSDictionary *options = [NSDictionary dictionaryWithObject:
[NSNumber numberWithBool:YES] forKey:NSPasteboardURLReadingFileURLsOnlyKey];

NSArray *fileURLs =
[pasteboard readObjectsForClasses:classes options:options];

That's straight from Apple's Pasteboard Programming Guide.

MacOS and Swift 3 - how to pass result from one filter to another

Seems to be the same issue with this:

CIGaussianBlur and CIAffineClamp on iOS 6

Please try this:

    let cgImage = context.createCGImage(result, from: ciImage.extent)

How to copy text to clipboard/pasteboard with Swift

If all you want is plain text, you can just use the string property. It's both readable and writable:

// write to clipboard
UIPasteboard.general.string = "Hello world"

// read from clipboard
let content = UIPasteboard.general.string

(When reading from the clipboard, the UIPasteboard documentation also suggests you might want to first check hasStrings, "to avoid causing the system to needlessly attempt to fetch data before it is needed or when the data might not be present", such as when using Handoff.)

Can I receive a callback whenever an NSPasteboard is written to?

Unfortunately the only available method is by polling (booo!). There are no notifications and there's nothing to observe for changed pasteboard contents. Check out Apple's ClipboardViewer sample code to see how they deal with inspecting the clipboard. Add a (hopefully not overzealous) timer to keep checking for differences and you've got a basic (if clunky) solution that should be App-Store-Friendly.

File an enhancement request at bugreporter.apple.com to request notifications or some other callback. Unfortunately it wouldn't help you until the next major OS release at the earliest but for now it's polling until we all ask them to give us something better.



Related Topics



Leave a reply



Submit