I would like to get the text from the clipboard. I have write a code that seems to work but sometimes it crashes, for example when I try to use the app when I login as guest user. Maybe because the Pasterboard could not contain text.
This is the code I'm using, I would like to wrap the last line in a conditional statement, but it seem too late to done that because at that point I receive an error.
func pasteOverAction() {
// create a pasteboard instance
let pasteboard = NSPasteboard.general()
// create an array for put pasteboard content
var clipboardItems: [String] = []
// iterate elements in pasteboard
for element in pasteboard.pasteboardItems! {
// if it's text
if let str = element.string(forType: "public.utf8-plain-text") {
clipboardItems.append(str) // put in the array
}
}
// put the first element of the array in a constant
// sometimes crashes here
let firstStringOfClipboard = clipboardItems[0]
}