Reputation: 1239
is there any Clipboard Change Event in swift? how can i get notified when clipboard changed in iOS application thanks
Upvotes: 11
Views: 11352
Reputation: 78
Solution:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// ...
// Clipboard
NotificationCenter.default.addObserver(self, selector: #selector(internalClipboardChanged), name: UIPasteboard.changedNotification, object: nil)
// ...
}
func sceneDidBecomeActive(_ scene: UIScene) {
// ...
self.clipboardChanged()
}
// CLIPBOARD
@objc func internalClipboardChanged() {
// ...
self.clipboardChanged()
}
func clipboardChanged() {
if (UIPasteboard.general.hasImages) {
self.controller!.clipboardImage = UIPasteboard.general.image
} else {
self.controller!.clipboardImage = nil
}
}
Upvotes: 0
Reputation: 25261
Here is a copy-able swift 5.0 version
NotificationCenter.default.addObserver(self, selector: #selector(clipboardChanged),
name: UIPasteboard.changedNotification, object: nil)
And further, if you want to get the text in your clipboard in this event,
@objc func clipboardChanged(){
let pasteboardString: String? = UIPasteboard.general.string
if let theString = pasteboardString {
print("String is \(theString)")
// Do cool things with the string
}
}
Upvotes: 19
Reputation: 15784
You can capture UIPastedboardChangedNotification as described in this link:
Example: (impossible to make the code appeared correctly, I've pasted an image.
Add notification to your didFinishLaunchingwithOptions call-back in AppDelegate
Add function to handle when UIPastedboardChangedNotification sent to you AppDelegate
Upvotes: 3