10

is there any Clipboard Change Event in swift? how can i get notified when clipboard changed in iOS application thanks

nmokkary
  • 1,219
  • 3
  • 14
  • 24

3 Answers3

19

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
        }
    }
Allan Spreys
  • 5,287
  • 5
  • 39
  • 44
Fangming
  • 24,551
  • 6
  • 100
  • 90
  • It should be noted that this is **iOS only**. MacOS does not seem to have an equivalent notification, all the soltions I found are timer-based. – soundflix Aug 21 '23 at 21:59
3

You can capture UIPastedboardChangedNotification as described in this link:

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIPasteboard_Class/index.html#//apple_ref/c/data/UIPasteboardChangedNotification

Example: (impossible to make the code appeared correctly, I've pasted an image.

  1. Add notification to your didFinishLaunchingwithOptions call-back in AppDelegate

  2. Add function to handle when UIPastedboardChangedNotification sent to you AppDelegate

enter image description here

Duyen-Hoa
  • 15,384
  • 5
  • 35
  • 44
  • this code worked in my app but if i copy a text out of app it not worked. please help me – nmokkary Apr 09 '15 at 08:07
  • this may cause memory warning. is there any other option for my question. i want to check when a user copy a text twice. – nmokkary Apr 09 '15 at 08:16
  • up to do ate working link to `UIPasteboardChanged`: https://developer.apple.com/documentation/foundation/nsnotification.name/1622104-uipasteboardchanged – Chris Apr 26 '18 at 20:58
  • Thanks a lot Hoa ;-) Saved me a few headaches! – Ethenyl May 04 '19 at 20:44
0

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
    }
}