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
DocumentGroup just needs a binding to the document to initialize the ContentView with, so have a func on the document grab the url & return the binding:
App:
import SwiftUI
@main
struct FileOpenApp: App {
var body: some Scene {
DocumentGroup(newDocument: FileOpenDocument()) { file in
ContentView(document: file.document.setSourceURL(file))
}
}
}
Document:
struct FileOpenDocument: FileDocument {
var sourceURL: URL?
init() {
}
// needs to be mutating to avoid "self is immutable" error
mutating func setSourceURL(_ config: FileDocumentConfiguration< FileOpenDocument >) -> Binding<FileOpenDocument> {
sourceURL = config.fileURL
return config.$document
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With