2017-04-04 69 views
0

我想從剪貼板中獲取文本。我編寫了一個似乎可以正常工作的代碼,但有時會崩潰,例如,當我以guest用戶身份登錄時,嘗試使用該應用程序時。也許是因爲Pasterboard不能包含文字。嘗試從macOS中的粘貼板獲取文本時出現錯誤

這是我正在使用的代碼,我想將最後一行包含在條件語句中,但似乎太晚了,因爲那時我收到一個錯誤。

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] 
} 
+1

你的問題是'.pasteboardItems!'。你不應該強制解開一個可選的。相反,處理這個屬性爲零的可能性。 – Moritz

+1

UTI類型應該是「public.plain-text」 –

回答

0

我發現了這個問題。當在剪貼板中還沒有文本時(例如,當您剛剛使用訪客用戶登錄時),創建的數組中沒有項目,並且出現超出範圍的錯誤。我通過添加一個檢查來解決這個錯誤。

除了虛線之間的部分外,代碼與問題的代碼類似。

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] 
} 
相關問題