I'm trying to implement a simple drag and drop of a String
from ViewA
to ViewB
, on a macOS SwiftUI app, but my NSItemProvider.loadObject(ofClass:completionHandler:)
always fails with the error "Could not coerce an item to class NSString".
ViewA(element: myElement)
.onDrag { NSItemProvider(object: myElement.title as NSString) }
ViewB()
.onDrop(of: [.plainText], isTargeted: nil, perform: { providers, location in
_ = providers.first?.loadObject(ofClass: NSString.self, completionHandler: { text, error in
print("Dropped \(text?.description ?? "?") with error: \(error?.localizedDescription ?? "")")
})
return true
})
Some things to notice:
- The same code works as expected on iOS/iPadOS.
- If instead I try to drag and drop a
URL
by changingmyElement.title
to URL, and changing the specific item providers to handle the URL, the code also works as expected. - I found a Reddit post from 6 months ago with the exact same problem.
I have created a simple project with the issue: https://github.com/marcosatanaka/drag-and-drop-string
How can I load a string from NSItemProvider
, so I can drag and drop it from one view to the other, on macOS? Is this a bug or am I doing something wrong?