'Get URL from Open dialog of standard Swift document-based application

I am trying to extract the URL of the document a user has selected in the default "Open" dialogue of my document based macOS application. I understand, a fileWrapper is passed to the init method but is there a way of extracting the path/URL from said wrapper?

Thanks,

Lars



Solution 1:[1]

The FileWrapper has a filename field, so you'd presumably use that.

Solution 2:[2]

The open panel gives you the URL if someone clicks the Open (OK) button. NSOpenPanel has a urls property that contains the URLs of the selected files.

SwiftUI file importers give you a URL if the open was successful.

.fileImporter(isPresented: $isImporting, allowedContentTypes: 
    [.png, .jpeg, .tiff], onCompletion: { result in
    
    switch result {
        case .success(let url):
            // Use the URL to do something with the file.
        case .failure(let error):
            print(error.localizedDescription)
    }
})

UPDATE

SwiftUI's document opening panel works differently than the file importer. You could try working with NSOpenPanel directly. The folllowing article should help:

Save And Open Panels In SwiftUI-Based macOS Apps

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Blindy
Solution 2