DanielZanchi
DanielZanchi

Reputation: 2768

How to copy a video to NSPasteboard as a file from a local URL (macOS)?

I have a mp4 video saved in a folder.
How can i copy the video from my app as a file, in order to paste it in other platforms like Telegram or the Finder to paste it as a new file? At the moment this is the function i wrote but it pastes the video only in a iMessage textField.

func copyVideo() {
    guard let url = TaskManager.shared.lastVideoURL else { return }
    do {
        let data = try Data(contentsOf: url)
        let pasteboard = NSPasteboard.general
        pasteboard.declareTypes([kUTTypeMPEG4 as NSPasteboard.PasteboardType], owner: nil)
        print(pasteboard.setData(data, forType: kUTTypeMPEG4 as NSPasteboard.PasteboardType))
    } catch {
        print("error getting data from video \(error)")
    }
}

What am I doing wrong?

Upvotes: 1

Views: 587

Answers (1)

DanielZanchi
DanielZanchi

Reputation: 2768

After some test I found the solution.
This method copies the video as a file:

func copyVideo() {      
    guard let url = TaskManager.shared.lastVideoURL else { return }
    if let fileRefURL = (url as NSURL).fileReferenceURL() as NSURL? {
        print(fileRefURL)
        let pasteboard = NSPasteboard.general
        pasteboard.clearContents()
        pasteboard.writeObjects([fileRefURL])
        pasteboard.setString(fileRefURL.relativeString, forType: .fileURL)
    }
}

Upvotes: 3

Related Questions