---
title: "#45: Pasteboards 📋"
url: https://littlebitesofcocoa.com/45-pasteboards
author: Jake Marsh
published: 2015-07-24
topics: ["UIKit"]
description: "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: On iOS, similar..."
---

# #45: Pasteboards 📋

By Jake Marsh, July 24, 2015. HTML: https://littlebitesofcocoa.com/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

``` swift
// 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.

``` swift
// iOS

pb.string = "Delicious!"

// OS X

pb.clearContents()
pb.setString("Delicious!", forType: NSPasteboardTypeString)
```

## Read Contents

On OS X, you'll use the NSPasteboardType* family of keys.

``` swift
pb.string // iOS

pb.stringForType(NSPasteboardTypeString) // OS X
```

## Get Notified Of Changes

``` swift
// 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 {
    print(pb.items)
  }
}
```

## Share Data Between Apps

If you're using App Groups, you can share data between your apps by creating your own custom keyboard:

``` swift
let customPB = UIPasteboard(
  name: "com.littlebites.spaceships",
  create: true
)

customPB!.persistent = true
```

## Copy Animated GIF to Clipboard

``` swift
if let GIFData = NSData(contentsOfURL: GIFURL) {
  pb.setData(
    GIFData,
      forPasteboardType: "com.compuserve.gif"
  )
}
```
