Search code examples
swiftmacosswiftuidocument-based

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

  • 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
        }
    }