Ross Stepaniak
Ross Stepaniak

Reputation: 855

Why is clipboard UIPasteboardChanged notification fired twice?

I subscribed for clipboard text change notification. Every time something is copied into he clipboard in my app, it fires the event twice. In other words onCopy() is called twice. (xCode 8.1; iOS 9, 10)

import Foundation

protocol Clipboard {
    func onCopy()
}

class SecureClipboard : NSObject, Clipboard {
    static let sharedReader = SecureClipboard()
    private var clipboardContent: String?
    private var clipboardBeingCleared: Bool = false

    /// Lifycycle

    private override init() {
        super.init()
        subscribForClipboardChanges()
    }

    private func subscribForClipboardChanges() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(onCopy),
                                               name:NSNotification.Name.UIPasteboardChanged,
                                               object: nil)
    }

    /// Clipboard

    func onCopy() {
        // Called twice
    }
}

Upvotes: 4

Views: 593

Answers (1)

Alex
Alex

Reputation: 3981

It sends back notifications with info about how the pasteboard contents have changed, such as Added or Removed events. It does trigger twice for me for each pasteboard change events, but the user info it contains is different each time.

I debounced a short duration to ignore these, because I do not need any information contained in the notification's userInfo, otherwise, you could try to parse the contents and figure out exactly which ones you care about.

NotificationCenter.default
        .publisher(for: UIPasteboard.changedNotification)
        .debounce(for: .milliseconds(100), scheduler: DispatchQueue.main)

Upvotes: 0

Related Questions