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?
CodePudding user response:
I think you can fill a bug on this, after some debugging I thinks the problem come from the creation of the provider item.
On iOS we receive this provider :
<UIItemProvider: 0x600000198000> {types = (
"public.utf8-plain-text"
)}
When on macOS we receive this provider:
<NSItemProvider: 0x600000374540> {types = (
)}
As you can see the item providers is empty on types, that why you can't load it. Without the type the system can't load it.