Yakuhzi
Yakuhzi

Reputation: 1269

How to properly register a failable load handler for an NSItemProvider

When registering a file representation to NSItemProvider for a SwiftUI view and calling the completionHandler of the registerFileRepresentation method with a nil argument for the URL, the next time an NSItemProvider is created for the same destination, the loadHandler callback is simply not invoked.

SomeSwiftUIView()
    .itemProvider {
        let provider = NSItemProvider()
        provider.suggestedName = fileName
        provider.registerFileRepresentation(for: .data) { completionHandler in
            let fileURL = try? someThrowableOperationToGetTheFileURL()
            completionHandler(fileURL, false, nil) // fileURL can be 'nil'
            return nil
        }
        return provider
    }

The same thing also happens calling the completionHandler with a valid URL, but an Error as third argument. As long as the provider.suggestedName and the drop destination stays the same, the loadHandler callback will not be invoked anymore. Assigning a random string to the provider.suggestedName, or dropping the file to another directory will call the callback again until the completionHandler is again called with a nil URL or an Error.

Use case: Before I can pass the file url to the completionHandler, I first have to move the file to a specific directory. If an error occurs during this process, I have no URL to pass to the completionHandler, so I pass nil. But when I retry the same drag operation, the loadHandler callback is simply not invoked anymore.

I tried the same but using a Trasferable representation instead of NSItemProvider, but the issue is the same. When I throw an exception in the Transferable callback, it will never be called again.

Is there anything I can do so that this loadHandler callback is called again the next time I repeat the same drag & drop operation?

Upvotes: 0

Views: 31

Answers (0)

Related Questions