3

I have an iOS app which looks at the contents of the pasteboard and tries to do something (hopefully) intelligent with it. (The app requires iOS 9.3+ although at this point I imagine most people are using iOS 11.x.)

The problem is that my device (iPhone X) is always copying data from my MacBook Pro. For example, I can select and copy text on my MacBook, putting it into the pasteboard there. Then on my iPhone, I can select and copy text such as my email address, putting it onto the pasteboard there. But then when I run my app and try to access the pasteboard, it takes a few seconds and then uses the text from my MacBook!

This is especially annoying because it causes a delay while pulling the data across the network, making my UI unresponsive. I'd much rather just have the [UIPasteboard -hasStrings] method return immediately.

I know that I can use setItems:options: with an option value of UIPasteboardOptionLocalOnly when adding items so that those items will stay on the device and not get transferred to the MacBook. But that option doesn't prevent the pasteboard from automatically pulling in data from the MacBook.

Is there any way to prevent hasStrings from automatically pulling data from the remote laptop, without disabling that functionality entirely on the device (ie, I don't want to force the user to disable Handoff at the system-level for all apps).

Kenster999
  • 466
  • 2
  • 13

1 Answers1

0

Use async function to retrieve data and prevent blocking UI. Something like this:

func getStringFromClipboard(completion: @escaping (_ copiedString: String?) -> Void) {
    DispatchQueue.global(qos: .userInitiated).async {
        let pastboardString = UIPasteboard.general.string

        DispatchQueue.main.async {
            completion(pastboardString)
        }
    }
}

And then:

override func viewWillAppear(_ animated: Bool) {
    super.viewWilAppear(animated)
    getStringFromClipboard { (copiedString) in
        guard let copiedString = copiedString else {
            return
        }
        // your code if clipboard contains string
    }
}