Search code examples
swiftfoundation

How do I load a URL using NSItemProvider's new Async loadItem method?


I am having difficulty grabbing a fileURL in a DropDelegate in SwiftUI, when dragging a file from my desktop into my app.

I am using the async loadItem call on NSItemProvider which returns an NSSecureCoding. I assumed that I could cast the result to an NSURL but it always fails.

let url = try await (urlProvider
    .loadItem(forTypeIdentifier: UTType.url.identifier) as? NSURL

If I try to force the cast I get the following error:

Could not cast value of type 'Foundation.__NSSwiftData' to 'NSURL'.

I am successfully using the same call and casting to an NSDictionary elsewhere in my code.

This is in Xcode 13.4, Swift 5. I have read access to user selected files in my sandbox capabilities.

Can anyone help point out what I am doing wrong? Thank you.


Solution

  • I had to cast to Data and then construct the URL from that:

    if let data = try await urlProvider
        .loadItem(forTypeIdentifier: UTType.fileURL.identifier) as? Data {
        url = URL(dataRepresentation: data, relativeTo: nil) }