Get file path from .onDrop on macOS SwiftUI app

I'm building an app to manage and edit some files. To do that, I want to open the files in place dropping them into a view. I cannot find a way to obtain the file URL after the drop operation. If I constrain the file types to .fileURL, the drop frame doesn't activate. If I use .data, I get the file and not the path, which is what I want.

Any way to do this the SwiftUI way?

.onDrop(of: [.fileURL], isTargeted: $dragOver) { providers -> Bool in
providers.first?.loadDataRepresentation(forTypeIdentifier: "public.file-url", completionHandler: { (data, error) in
                            if let data = data {
                                print(data.description)
                            }
                        })
                        return true
}

Replies

To get the file URL after a drop operation, try this:

.onDrop(of: [.fileURL], isTargeted: nil) { providers in
    if let provider = providers.first(where: { $0.canLoadObject(ofClass: URL.self) } ) {
        let _ = provider.loadObject(ofClass: URL.self) { object, error in
            if let url = object {
                print("url: \(url)")
            }
        }
        return true
    }
    return false
}

(Tested on macOS)

Did that work for you, @airbolt?

Obviously can't speak for @airbolt. but does not work for me with iOS 16.2 in simulator. From what I can tell in my experimenting, it seems that even when dragging from the Files app, iOS only drops the content of a file (eg .plainText in my use case), not the file itself???