Swift 3 copy string to clipboard
Asked Answered
E

2

25

How do you Copy a string to Clipboard in macOS 10.12 with Xcode 8 and Swift 3? I am not able to find any reference.

Edan answered 8/12, 2016 at 12:12 Comment(4)
https://mcmap.net/q/433407/-writing-a-string-to-nspasteboardYul
you can see my comment in that answer, it does not work for Swift 3Edan
So try to update it. The documentation would probably be handy. As is autocompletion.Yul
Sorry, I only had to add import AppKit. What a stupid error!Edan
P
26

Swift 3 you copy it like this way.

 let pasteboard = NSPasteboard.general()
 pasteboard.declareTypes([NSPasteboardTypeString], owner: nil)
 pasteboard.setString("Good Morning", forType: NSPasteboardTypeString)
Pickard answered 8/12, 2016 at 12:15 Comment(7)
This is not for macOS but iOSEdan
Ok thank you, if you add import AppKit I will mark as best questionEdan
@LucaMarconato Edited answer for that.Pickard
I have tried and it does not work, after lunch I will try to fix itEdan
@LucaMarconato Edited the answer, there is no need to import the AppKit I have try this code and it is working perfectly.Pickard
Working perfectly (I still have to add AppKit)Edan
@LucaMarconato Welcome mate, I have tried this In Xcode 8 with Swift 3 and it is working without importing AppKit may be something else is missing.Pickard
A
36

In Swift 5.2 (on macOS 10.15) the answer is slightly different:

let pasteboard = NSPasteboard.general
pasteboard.declareTypes([.string], owner: nil)
pasteboard.setString("Good Morning", forType: .string)
Adolphadolphe answered 6/5, 2020 at 15:59 Comment(0)
P
26

Swift 3 you copy it like this way.

 let pasteboard = NSPasteboard.general()
 pasteboard.declareTypes([NSPasteboardTypeString], owner: nil)
 pasteboard.setString("Good Morning", forType: NSPasteboardTypeString)
Pickard answered 8/12, 2016 at 12:15 Comment(7)
This is not for macOS but iOSEdan
Ok thank you, if you add import AppKit I will mark as best questionEdan
@LucaMarconato Edited answer for that.Pickard
I have tried and it does not work, after lunch I will try to fix itEdan
@LucaMarconato Edited the answer, there is no need to import the AppKit I have try this code and it is working perfectly.Pickard
Working perfectly (I still have to add AppKit)Edan
@LucaMarconato Welcome mate, I have tried this In Xcode 8 with Swift 3 and it is working without importing AppKit may be something else is missing.Pickard

© 2022 - 2024 — McMap. All rights reserved.