Search code examples
macosswiftuidragnsimage

SwiftUI - onDrag Argument type 'NSImage' does not conform to expected type 'NSItemProviderWriting'


I'm trying several ways to implement image dragging (from my app to other apps) in macOS but none of them is working. The image is a Data() object, which was taken from the clipboard, not an URL.

My code:

.onDrag {
    return NSItemProvider(object: NSImage(data: self.item.value) ?? NSImage())
}

It says

Argument type 'NSImage' does not conform to expected type 'NSItemProviderWriting'

I tried with text and it's working. But can't find a way to drag an image.


Solution

  • The following works as Drag&Drop from testing SwiftUI app to TextEdit. Testing image image is stored in Assets.xcassets

    Image("image")
        .onDrag {
            NSItemProvider(item: NSImage(named: "image")?.tiffRepresentation as NSSecureCoding?, 
                           typeIdentifier: kUTTypeTIFF as String)
        }