NSPasteboard Example Using Swift

Hello,

I’ve been playing with swift, sort of got hit with dealing with the NSPasteboard. This is a focus program dealing with writing/reading to the pasteboard.

 import Cocoa
 // Dummy data
 let url1 = NSURL(fileURLWithPath: "/Users/LAROD/Desktop/file1.txt")?.absoluteURL
 let url2 = NSURL(fileURLWithPath: "/Users/LAROD/Desktop/file2.txt")?.absoluteURL
 let str = "This is a string."
// We create the pasteboard and clear the contents to make sure
// it only contains our objects.
 var pboard = NSPasteboard.generalPasteboard()
 pboard.clearContents()
// Writing three objects to the pasteboard, two urls and one string
 pboard.writeObjects(NSArray(objects: url1!, str, url2!))
// Reads only NSFilenamesPboardType, we don't care about the
// string pasteboardtype. You can filter the array returned if you
// need other PboardTypes.
 var files: AnyObject? = pboard.propertyListForType(NSFilenamesPboardType)
 println(files!)

Leave a Reply