0

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] 
}
Cue
  • 2,952
  • 3
  • 33
  • 54

1 Answers1

0

I discovered the problem. When in the clipboard there is not text yet (for example when you just logged in with a Guest User), the created array has no items and you get an out of range error. I solved by adding a check to avoid the error.

The code is similar to the one of the question, except for the part between dash lines.

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
        }
    }

    // Added part ----------------------------------------
    // avoid out of range if there is not a tex item
    let n = clipboardItems.count
    if n < 1 {
        NSBeep() // warn user that there is not text in clipboard
        return // exit from the method
    }
    // ---------------------------------------------------

    // put the first element of the array in a constant
    // now don't crashes here anymore
    let firstStringOfClipboard = clipboardItems[0] 
}
Cue
  • 2,952
  • 3
  • 33
  • 54