NEW: Master Swift design patterns with my latest book! >>

How to copy text to the clipboard using UIPasteboard

Written by Paul Hudson    @twostraws

You can write to and read from the iOS clipboard by using the UIPasteboard class, which has a generalPasteboard() method that returns the shared system method of copying and pasting data between apps. Using this you can write text to the clipboard just like this:

let pasteboard = UIPasteboard.general
pasteboard.string = "Hello, world!"

To read text back from the clipboard, you should unwrap its optional value like this:

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

Available from iOS 3.0

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Need to know Objective-C fast?

I wrote a book dedicated to teaching Objective-C to developers who already know Swift – it's the fastest way to get up to speed!

Click here to visit the Hacking with Swift store >>