Yiming Designer
Yiming Designer

Reputation: 685

Cannot drag image from my app to Desktop/Finder with SwiftUI `.onDrag` or `.draggable`

I'm writing an app in SwiftUI on macOS 13.1, and want to drag image from my app to Desktop/Finder. Referred to this post, I gave .onDrag a try with following code. But the dragging don't have any reaction no matter how and where I drag it.

enter image description here

struct ContentView: View {
    
    @State var image: NSImage = NSImage(imageLiteralResourceName: "demoImage")
    
    var body: some View {
        Image(nsImage: image)
            .resizable()
            .scaledToFit()
            .frame(width: 200, height: 200)
            .onDrag {
                NSItemProvider(item: image.tiffRepresentation as NSSecureCoding?, typeIdentifier: UTType.image.identifier)
            }
    }
}

If I change typeIdentifier from UTType.image.identifier to UTType.tiff.identifier, the image in my app can at least successfully be dragged to Apple Pages, but it still fails when dragging to Desktop/Finder.

Then I tried to replace .onDrag with .draggable(image.tiffRepresentation ?? Data()), but the outcome is in the same.

How can I solve this?

Upvotes: 2

Views: 588

Answers (2)

Yiming Designer
Yiming Designer

Reputation: 685

Inspired by @Ivan Ičin 's answer, I managed to have this code. Tested on macOS 13.1

Image(nsImage: image)
    .resizable()
    .scaledToFit()
    .frame(width: 200, height: 200)
    .onDrag {
        let fileURL = FileManager.default.homeDirectoryForCurrentUser.appending(component: "cover.png")
        // I extended `URL`, feel free to create file in your own way
        fileURL.createFile(contents: image.pngData)
                    
        return NSItemProvider(item: fileURL as NSSecureCoding, typeIdentifier: UTType.fileURL.identifier)
    }

Upvotes: 1

Ivan I
Ivan I

Reputation: 9990

The Finder does accept only files and folders (and file promises if you want to do something more complicated). As such the simplest thing would be to save the image on the disk and send the URL.

Upvotes: 0

Related Questions