在 swift 中收到有关剪贴板更改的通知

Get notified on clipboard change in swift

swift中是否有任何剪贴板更改事件? 当剪贴板在 iOS 应用程序中更改时,我如何得到通知 谢谢

您可以按照此 link:

中的描述捕获 UIPastedboardChangedNotification

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

示例:(无法使代码正确显示,我已粘贴图片。

  1. 在 AppDelegate 的 didFinishLaunchingwithOptions 回调中添加通知

  2. 添加函数来处理 UIPastedboardChangedNotification 发送给您 AppDelegate

这里是可复制的swift5.0版本

NotificationCenter.default.addObserver(self, selector: #selector(clipboardChanged),
                                               name: UIPasteboard.changedNotification, object: nil)

此外,如果您想在此活动中获取剪贴板中的文本,

    @objc func clipboardChanged(){
        let pasteboardString: String? = UIPasteboard.general.string
        if let theString = pasteboardString {
            print("String is \(theString)")
            // Do cool things with the string
        }
    }

解决方案:

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