How to copy image from pasteboard and write image to pasteboard in mac app

I am trying to copy image from pasteboard and write image to pasteboard but after setting data to pasteboard i am not able to paste image anywhere in system. below block of code which i am using.


   // Copying image data from paste board
            let pasteboard = NSPasteboard.general
            let imageData = pasteboard.data(forType: NSPasteboard.PasteboardType.tiff)
           
           
            //Writing image data to paste board
           
            let pb = NSPasteboard.general
           
            pb.declareTypes([NSPasteboard.PasteboardType.tiff], owner: nil)
           
            if let imageData = imageData.tiffRepresentation{
                print("imagedata \(imageData)")
                pb.clearContents()
                pb.setData(imageData, forType: NSPasteboard.PasteboardType(rawValue: "NSTIFFPboardType"))
            }
Post not yet marked as solved Up vote post of premk Down vote post of premk
4.2k views

Replies

Instead of setData you should use writeObjects(_:) like this:

    func writeImageToPasteboard(img: NSImage)
    {
        let pb = NSPasteboard.general
        pb.clearContents()
        pb.writeObjects([img])
    }
   
    func pasteboardImage() -> NSImage?
    {
        let pb = NSPasteboard.general
        let type = NSPasteboard.PasteboardType.tiff
        guard let imgData = pb.data(forType: type) else { return nil }
       
        return NSImage(data: imgData)
    }