Reputation: 916
How can I check if there is something on the clipboard?
if there is something on the clipboard, then perform a certain action, and if not, another action (as shown in the code for an example)
if (if in the clipboard, that is, then open the VC) {
let modalViewController = self.storyboard?.instantiateViewController(withIdentifier: "Clipboard") as? ClipboardViewController
modalViewController?.modalPresentationStyle = .overCurrentContext
self.present(modalViewController!, animated: true, completion: nil)
} else (if the clipboard is empty then) {
let alert = UIAlertController(title: "Clipboard is Empty", message: "It's recommended you bring your towel before continuing.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "No", style: .cancel, handler: nil))
self.present(alert, animated: true)
}
Upvotes: 6
Views: 3871
Reputation: 236275
Since iOS 10 you should use UIPasteboard
properties like hasStrings
to check if a specific data type is present on Pasteboard:
var hasStrings: Bool
Returns a Boolean value indicating whether or not the strings property contains a nonempty array.
From the docs:
Starting in iOS 10, the UIPasteboard class provides properties for directly checking whether specific data types are present on a pasteboard, described in Checking for Data Types on a Pasteboard. Use these properties, rather than attempting to read pasteboard data, to avoid causing the system to needlessly attempt to fetch data before it is needed or when the data might not be present. For example, you can use the new hasStrings property to determine whether to present a string-data Paste option in the user interface, using code like this:
if UIPasteboard.general.hasStrings {
// Enable string-related control...
if let string = UIPasteboard.general.string {
// use the string here
}
}
There is another few properties to check for data types;
var hasColors: Bool
Returns a Boolean value indicating whether or not the colors property contains a nonempty array.
var hasImages: Bool
Returns a Boolean value indicating whether or not the images property contains a nonempty array.
var hasURLs: Bool
Returns a Boolean value indicating whether or not the urls property contains a nonempty array.
Upvotes: 7
Reputation: 6018
You should use UIPasteboard class.
if let value = UIPasteboard.general.string {
// there is value in clipboard
} else {
// clipboard is empty
}
Upvotes: 6