I want Swift (OS X, Cocoa application) to detect a change in clipboard value.
Currently, we are able to get the clipboard value, and we are able to reflect it on the label by pressing the button.
The next step is to reflect the value of the clipboard on the label, but how do you do it?
@IBAction func pushedButton (sender:AnyObject) {
// Get value from clipboard
let pb = NSPasteboard.generalPasteboard()
iflet aaa=pb.stringForType(NSPasteboardTypeString){
label2.stringValue=aaa
} else {
label2.stringValue="Clipboard is empty"
}
}
Unfortunately, for NSPasteboard
,
So I guess I have no choice but to poll myself (see if there are any changes on a regular basis).
I would like to introduce you to someone who posted the monitoring class code written in Swift on Question of our Stack Overflow home.(I'm just using the NSTimer
to periodically check for changes in the NSPasteboard
state.)
Swift 2.2 calls the delete method only when a warning code is issued and a file URL with a specific extension is written, but you should study it yourself and rewrite it to suit your needs.(Some of the protocol declarations for delete are missing in the article, but please point to the source of the link.)
It looks like this.
// Keep the appropriate class (usually AppDelegate or ViewController) compliant with 'PasteboardWatcherDelegate'
class MyClass —PasteboardWatcherDelegate/*, ...*/{
// Monitoring objects must be retained for the duration you want to monitor
private var watcher —PasteboardWatcher!
// In the initialization method
func myMethod(){
watcher = PasteboardWatcher (fileKinds: ["png", "jpg")
// Since circular references are available as they are, the original source, `var delete:PasteboardWatcherDelegate?`, will be used as a reference.
// `weak vardelegate: PasteboardWatcherDelegate?`
watcher.delegate=self
}
// Implementation of the `PasteboardWatcherDelegate` method
func newlyCopiedUrlObtained (copiedUrl copiedUrl:NSURL) {
// This method is called if the file URL string has the specified extension
print(copiedUrl)
}
}
I'm sorry, but I haven't tried to see how useful it is.(You may need to make some modifications to the above.) The questions in the article I introduced were written more than 5 years ago, but Apple still doesn't work, so you might not want certain apps to easily monitor and monopolize the content of the clipboard, which is supposed to be shared throughout the system.
© 2024 OneMinuteCode. All rights reserved.