Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 777
nonresidentalien Avatar asked Nov 02 '25 17:11

nonresidentalien


2 Answers

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
    }
} 
like image 90
nonresidentalien Avatar answered Nov 04 '25 08:11

nonresidentalien


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

like image 23
Swift Dev Journal Avatar answered Nov 04 '25 07:11

Swift Dev Journal