Search code examples
swiftmacosswift3nspasteboard

Reading from the clipboard with Swift 3 on macOS


I'm a beginner with Swift, and I'm trying to figure out how can I read what has been copied to the clipboard On macOS (Swift 3)? I've searched a lot but can't seem to find anything that works.

A few of the things I've tried from online:

var pasteboardItems: [NSPasteboardItem]? { get }
print("\(pasteboardItems)")

and

let pb = NSPasteboard.general()
pb.string(forType: NSPasteboardTypeString)

print("\(pb)")

and

let pasteboard = UIPasteboard.general
if let string = pasteboard.string {
    // text was found and placed in the "string" constant
}

and lastly

func paste(sender: AnyObject?) {

    let pasteboard = NSPasteboard.generalPasteboard()

    if let nofElements = pasteboard.pasteboardItems?.count {

        if nofElements > 0 {


            // Assume they are strings

            var strArr: Array<String> = []
            for element in pasteboard.pasteboardItems! {
                if let str = element.stringForType("public.utf8-plain-text") {
                    strArr.append(str)
                }
            }


            // Exit if no string was read

            if strArr.count == 0 { return }


            // Perform the paste operation

            dataSource.cmdPaste(strArr)
       }
    }        
}

Solution

  • Works for Swift 3 and Swift 4

    // Set string to clipboard
    let pasteboard = NSPasteboard.general
    pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
    pasteboard.setString("Good Morning", forType: NSPasteboard.PasteboardType.string)
    
    var clipboardItems: [String] = []
    for element in pasteboard.pasteboardItems! {
        if let str = element.string(forType: NSPasteboard.PasteboardType(rawValue: "public.utf8-plain-text")) {
            clipboardItems.append(str)
        }
    }
    
    // Access the item in the clipboard
    let firstClipboardItem = clipboardItems[0] // Good Morning