Tag Archives: UIPasteboard

How to use UIPasteboard to share data with iOS

Screen Shot 2015-02-02 at 11.56.41

UIPasteboard allows you to copy data to iOS and paste it back into your own or other apps. Think of copying text from a Pages document and pasting it into an email. That’s UIPasteboard hard at work.

The class supports NSString, UIImage, NSURL and UIColor out of the box. You can add your own items to the pasteboard like this:

To retrieve the value:

The principle is the same for the other data types.

Copying and Pasting multiple items

Single values aside, UIPasteboard also has the ability to store the above data types as an NSArray. IF you had multiple values you’d like to add, you can use this:

This works with strings, images, URLs and colors.

Binary Data

UIPasteboard can also handle binary data from an NSData object. Here’s how to set data:

and to retrieve your data

The dataForPasteboardType parameter is an NSString of your choosing so that you can identify it as your data. Apple recommend to use the reverse DNS structure like com.yourdomain.yourapp.yourdata.

Creating your own Pasteboards

If you don’t want to share data with the general iOS Pasteboard, you can create your own:

To retrieve values from it in other classes, instantiate it again and pass NO as the create parameter.

The Find Pasteboard Myth

According to Apple’s documentation, there’s also the Find Pasteboard. Legend has it that it holds the latest string from Spotlight search. We should be able to access it like this:

which sadly doesn’t work. Even though the object exists and is valid, all of its properties are always nil, no matter how are we search for things. It’s therefore best to forget the Find Pasteboard exists and never mention it again.

How to access values from the iOS Clipboard (from copy and cut operations)

Screen Shot 2014-09-03 at 16.39.32iOS has a class called UIPasteboard which lets you access the last value that a user has copied or cut to the clipboard (or pasteboard).

The class has a singleton which lets you access a string like so:

This will work fine when any kind of text is involved. Copy/Cut/Paste is also available for images from the Photos app though, and you can access the latest UIImage like this:

Note that those two values are mutually exclusive: if you’ve copied an image, then the text string will be nil, and when you’ve copied text then the image value will be nil.

The UIPasteboard class is very versatile and lets you do all kinds of things – check out the Class Reference for more information: