1

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 changing myElement.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?

2
  • Hi, I tried your code and it's actually working can give a full example of failing ? Commented Nov 16, 2021 at 23:08
  • Hi @Hikosei, I forgot to mention that this occurs on a macOS app. I'm going to update the question and add a sample project. Commented Nov 17, 2021 at 11:34

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for the details. Indeed, it appears to be a macOS bug. I'm going to open a feedback about it.
Hello @MarcosTanaka , I thinks a find a duplicate of you question , I tried and it worked : stackoverflow.com/a/69325742/2873694 please give it a try

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.