How to copy text to clipboard/pasteboard with Swift

IosSwiftCocoa TouchCopyUipasteboard

Ios Problem Overview


I'm looking for a clean example of how to copy text to iOS clipboard that can then be used/pasted in other apps.

The benefit of this function is that the text can be copied quickly, without the standard text highlighting functions of the traditional text copying.

I am assuming that the key classes are in UIPasteboard, but can't find the relevant areas in the code example they supply.

Ios Solutions


Solution 1 - Ios

If all you want is plain text, you can just use the string property. It's both readable and writable:

// write to clipboard
UIPasteboard.general.string = "Hello world"

// read from clipboard
let content = UIPasteboard.general.string

(When reading from the clipboard, the UIPasteboard documentation also suggests you might want to first check hasStrings, "to avoid causing the system to needlessly attempt to fetch data before it is needed or when the data might not be present", such as when using Handoff.)

Solution 2 - Ios

Since copying and pasting is usually done in pairs, this is supplemental answer to @jtbandes good, concise answer. I originally came here looking how to paste.

iOS makes this easy because the general pasteboard can be used like a variable. Just get and set UIPasteboard.general.string.

Here is an example showing both being used with a UITextField:

Copy

UIPasteboard.general.string = myTextField.text

Paste

if let myString = UIPasteboard.general.string {
    myTextField.insertText(myString)
}

Note that the pasteboard string is an Optional, so it has to be unwrapped first.

Solution 3 - Ios

Copying text from the app to the clipboard:

let pasteboard = UIPasteboard.general
pasteboard.string = employee.phoneNumber

Solution 4 - Ios

SWIFT 4

UIPasteboard.general.string = "TEXT"

Solution 5 - Ios

in Swift 5 i can copy text to clipboard using

UIPasteboard.general.string = "Hello world"

then you can paste the text anywhere of your device

Solution 6 - Ios

Write below the code where you want to Copying String or Text

UIPasteboard.general.string = "Dhaval Gevariya" // Put your String here

this is for read String from clipboard.

var readString = UIPasteboard.general.string

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGarry LawView Question on Stackoverflow
Solution 1 - IosjtbandesView Answer on Stackoverflow
Solution 2 - IosSuragchView Answer on Stackoverflow
Solution 3 - IosRaj JoshiView Answer on Stackoverflow
Solution 4 - IosÁlvaro AgüeroView Answer on Stackoverflow
Solution 5 - IosMenon HasanView Answer on Stackoverflow
Solution 6 - IosDhaval GevariyaView Answer on Stackoverflow