How to copy text to clipboard/pasteboard with Swift
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.)
SwiftUI - how to copy text to clipboard?
Use the following - put shown text into pasteboard for specific type (and you can set as many values and types as needed)
Update: for Xcode 13+, because of "'kUTTypePlainText' was deprecated in iOS 15.0..." warning
import UniformTypeIdentifiers
Text(self.BLEinfo.sendRcvLog)
.onTapGesture(count: 2) {
UIPasteboard.general.setValue(self.BLEinfo.sendRcvLog,
forPasteboardType: UTType.plainText.identifier)
}
for older versions:
import MobileCoreServices // << for UTI types
// ... other code
Text(self.BLEinfo.sendRcvLog)
.onTapGesture(count: 2) {
UIPasteboard.general.setValue(self.BLEinfo.sendRcvLog,
forPasteboardType: kUTTypePlainText as String)
}
Copy to clipboard using Javascript in iOS
Update! iOS >= 10
Looks like with the help of selection ranges and some little hack it is possible to directly copy to the clipboard on iOS (>= 10) Safari. I personally tested this on iPhone 5C iOS 10.3.3 and iPhone 8 iOS 11.1. However, there seem to be some restrictions, which are:
- Text can only be copied from
<input>
and<textarea>
elements. - If the element holding the text is not inside a
<form>
, then it must becontenteditable
. - The element holding the text must not be
readonly
(though you may try, this is not an "official" method documented anywhere). - The text inside the element must be in selection range.
To cover all four of these "requirements", you will have to:
- Put the text to be copied inside an
<input>
or<textarea>
element. - Save the old values of
contenteditable
andreadonly
of the element to be able to restore them after copying. - Change
contenteditable
totrue
andreadonly
tofalse
. - Create a range to select the desired element and add it to the window's selection.
- Set the selection range for the entire element.
- Restore the previous
contenteditable
andreadonly
values. - Run
execCommand('copy')
.
This will cause the caret of the user's device to move and select all the text in the element you want, and then automatically issue the copy command. The user will see the text being selected and the tool-tip with the options select/copy/paste will be shown.
Now, this looks a little bit complicated and too much of an hassle to just issue a copy command, so I'm not sure this was an intended design choice by Apple, but who knows... in the mean time, this currently works on iOS >= 10.
With this said, polyfills like this one could be used to simplify this action and make it cross-browser compatible (thanks @Toskan for the link in the comments).
Working example
To summarize, the code you'll need looks like this:
function iosCopyToClipboard(el) {
var oldContentEditable = el.contentEditable,
oldReadOnly = el.readOnly,
range = document.createRange();
el.contentEditable = true;
el.readOnly = false;
range.selectNodeContents(el);
var s = window.getSelection();
s.removeAllRanges();
s.addRange(range);
el.setSelectionRange(0, 999999); // A big number, to cover anything that could be inside the element.
el.contentEditable = oldContentEditable;
el.readOnly = oldReadOnly;
document.execCommand('copy');
}
Note that the el
parameter to this function must be an <input>
or a <textarea>
.
Old answer: previous iOS versions
On iOS < 10 there are some restrictions for Safari (which actually are security measures) to the Clipboard API:
- It fires
copy
events only on a valid selection andcut
andpaste
only in focused editable fields. - It only supports OS clipboard reading/writing via shortcut keys, not through
document.execCommand()
. Note that "shorcut key" means some clickable (e.g. copy/paste action menu or custom iOS keyboard shortcut) or physical key (e.g. connected bluetooth keyboard). - It doesn't support the
ClipboardEvent
constructor.
So (at least as of now) it's not possible to programmatically copy some text/value in the clipboard on an iOS device using Javascript. Only the user can decide whether to copy something.
It is however possible to select something programmatically, so that the user only has to hit the "Copy" tool-tip shown on the selection. This can be achieved with the exact same code as above, just removing the execCommand('copy')
, which is indeed not going to work.
How to copy string to clipboard
Did you refered this link : https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/UsingCopy,Cut,andPasteOperations/UsingCopy,Cut,andPasteOperations.html
The amount of code you have shared seems ok to copy text. May be more code will be helpful to understand your problem. Meanwhile you can go through this link , it is really helpful.
Make clipboard copy-paste work on iphone devices
Try this. Works for me.
var copy = function(elementId) {
var input = document.getElementById(elementId); var isiOSDevice = navigator.userAgent.match(/ipad|iphone/i);
if (isiOSDevice) { var editable = input.contentEditable; var readOnly = input.readOnly;
input.contentEditable = true; input.readOnly = false;
var range = document.createRange(); range.selectNodeContents(input);
var selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);
input.setSelectionRange(0, 999999); input.contentEditable = editable; input.readOnly = readOnly;
} else { input.select(); }
document.execCommand('copy');}
<input type="text" id="foo" value="text to copy" /><button onclick="copy('foo')">Copy text</button>
Related Topics
How to Set Image as a Title to Uinavigationbar
Disable Scroll on a Uiwebview Allowed
What Happens with Constraints When a View Is Removed
Notify Watchkit App of an Update Without the Watch App Requesting It
iOS Present Modal View Controller on Startup Without Flash
Custom Url Scheme for New Facebook iOS App
How to Integrate Linphone into an Existing Project (Sip in iOS)
Tableview Rounded Corners and Shadow
Delay/Wait in a Test Case of Xcode UI Testing
Differencebetween the App Id and the Bundle Id? Where Is the App Id in the Xcode Project
How to Remove All Navigationbar Back Button Title
Uinavigationcontroller Without Navigation Bar
iOS Tesseract Ocr Image Preperation
Profile Doesn't Match the Entitlements File's Value for the Application-Identifier Entitlement
App Transport Security Xcode 7 Beta 6
Icloud + Coredata - How to Avoid Pre-Filled Data Duplication