I have an iOS
app where I'm trying to paste something previously copied to the user's UIPasteboard
. I came across the UIPasteControl
as an option for a user to tap to silently paste without having the prompt "Allow Paste" pop up.
For some reason, despite having what seemingly is the correct configurations for the UIPasteControl, on testing a tap, nothing is called. I expected override func paste(itemProviders: [NSItemProvider])
to fire, but it does not.
Any help would be appreciated as there doesn't seem to be much info anywhere regarding UIPasteControl
.
import UIKit
import UniformTypeIdentifiers
class ViewController: UIViewController {
private let pasteControl = UIPasteControl()
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .systemBackground
pasteControl.target = self
pasteConfiguration = UIPasteConfiguration(acceptableTypeIdentifiers: [
UTType.text.identifier,
UTType.url.identifier,
UTType.plainText.identifier
])
//Tried setting pasteControl's pastConfiguration, and got the same result.
//pasteControl.pasteConfiguration = UIPasteConfiguration(
//acceptableTypeIdentifiers: [
//UTType.text.identifier,
//UTType.url.identifier,
//UTType.plainText.identifier
//]
//)
view.addSubview(pasteControl)
pasteControl.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
pasteControl.centerXAnchor.constraint(equalTo: view.centerXAnchor),
pasteControl.centerYAnchor.constraint(equalTo: view.centerYAnchor),
])
}
}
extension ViewController {
override func paste(itemProviders: [NSItemProvider]) {
for provider in itemProviders {
if provider.hasItemConformingToTypeIdentifier(UTType.url.identifier) {
provider.loadObject(ofClass: URL.self) { [weak self] reading, _ in
guard let url = reading as? URL else { return }
print(url)
}
}
else if provider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) {
provider.loadObject(ofClass: NSString.self) { [weak self] reading, _ in
guard let nsstr = reading as? NSString else { return }
let str = nsstr as String
if let url = URL(string: str) {
print(url)
}
}
}
}
}
}
You need to setup the UIPasteControl
with a UIPasteControl.Configuration
.
Change the line:
private let pasteControl = UIPasteControl()
to:
private let pasteControl = UIPasteControl(configuration: .init())
and the paste control will start working as expected.
Of course you might want to refactor that code a bit so you can set some properties as desired for the configuration.