How to Copy Text to Clipboard in Swift

Written by

in

Quick answer: Use UIPasteboard.general.string to write text to the clipboard and read it back. Set the string property to copy, and check hasStrings before reading to avoid unnecessary system fetches.

Why this happens

Developers often need to copy text programmatically without user selection gestures. The iOS clipboard (pasteboard) is exposed through UIPasteboard, but its API surface is small and the documentation can be sparse on practical patterns. The general pasteboard acts like a global string variable, yet developers miss the optional nature of the read path and the hasStrings optimization hint.

The key classes are UIPasteboard and its shared general instance. Writing is a single property assignment; reading returns an optional string because the pasteboard may be empty or contain non-text data. Apple recommends checking hasStrings first when reading, especially with Handoff, to prevent the system from fetching data unnecessarily.

How to fix it

1. Copy plain text to the clipboard

The simplest way to place text on the general pasteboard:

import UIKit

func copyToClipboard(_ text: String) {
    UIPasteboard.general.string = text
}

Call this with any string. The assignment overwrites the previous clipboard contents.

2. Paste text from the clipboard safely

Reading returns an optional. Guard against nil and use hasStrings to avoid a needless fetch:

func pasteFromClipboard() -> String? {
    guard UIPasteboard.general.hasStrings else { return nil }
    return UIPasteboard.general.string
}

3. Wire it to a UITextField (copy and paste)

A common pattern is copying the field’s text and pasting into the same or another field:

@IBAction func copyButtonTapped(_ sender: UIButton) {
    UIPasteboard.general.string = textField.text
}

@IBAction func pasteButtonTapped(_ sender: UIButton) {
    if let clipboardText = UIPasteboard.general.string {
        textField.insertText(clipboardText)
    }
}

insertText(_:) respects the current cursor position and selection, which is usually what you want.

4. Handle rich text or other data types (advanced)

If you need attributed strings, images, or custom UTIs, use the typed APIs:

// Attributed string
let attributed = NSAttributedString(string: "Bold", attributes: [.font: UIFont.boldSystemFont(ofSize: 17)])
UIPasteboard.general.setValue(attributed, forPasteboardType: kUTTypeRTF as String)

// Read back
if let data = UIPasteboard.general.data(forPasteboardType: kUTTypeRTF as String),
   let attributed = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil) {
    // use attributed
}

Import UniformTypeIdentifiers (or MobileCoreServices on older SDKs) for the UTI constants.

How to prevent it

  • Always unwrap UIPasteboard.general.string before using it; the pasteboard can be empty.
  • Check hasStrings before reading when the pasteboard might be stale or when using Handoff.
  • Don’t assume the clipboard contains text—users may have copied an image or file.
  • For sensitive data, consider UIPasteboard with isPersistent = false or use a named, non-persistent pasteboard.
  • Test on device; the simulator clipboard shares the Mac clipboard, which can mask bugs.

FAQ

Does UIPasteboard work in SwiftUI?

Yes. UIPasteboard is a UIKit class but is fully available in SwiftUI views. Call the same APIs from button actions or gesture handlers.

Why is the pasted string nil even after I copied?

The general pasteboard may have been cleared by another app, or the copied item was not plain text (e.g., an image). Always guard the optional and verify hasStrings.

Can I copy without the user seeing a “Paste” menu?

Yes. Programmatic UIPasteboard.general.string = "..." writes silently. The system paste menu only appears when the user long-presses in a text field.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 4.0; this article is shared under the same license.