#45: Pasteboards πŸ“‹


There's a ton of great functionality packed in the UIPasteboard and NSPasteboard classes. Let's take a look at some things you can do:

Get the System Pasteboard

// iOS

let pb = UIPasteboard.generalPasteboard()

// OS X

let pb = NSPasteboard.generalPasteboard()

Copy to Clipboard

On iOS, similar convenience methods exist for images, URLs, and colors.

// iOS

pb.string = "Delicious!"

// OS X

pb.setString("Delicious!", forType: NSPasteboardTypeString)

Read Contents

On OS X, you'll use the NSPasteboardType* family of keys.

pb.string // iOS

pb.stringForType(NSPasteboardTypeString) // OS X

Get Notified Of Changes

// iOS only. On OS X, you'll need to poll :(

NSNotificationCenter.defaultCenter().addObserver(   self,   selector: "pasteboardChanged:",
  name: UIPasteboardChangedNotification,
  object: nil

func pasteboardChanged(n: NSNotification) {
  if let pb = n.object as? UIPasteboard {

Share Data Between Apps

If you're using App Groups, you can share data between your apps by creating your own custom keyboard:

let customPB = UIPasteboard(
  name: "com.littlebites.spaceships",
  create: true

customPB!.persistent = true

Copy Animated GIF to Clipboard

if let GIFData = NSData(contentsOfURL: GIFURL) {
      forPasteboardType: "com.compuserve.gif"