In AppKit, NSSavePanel can be used to ask the user for a destination URL before the app creates a file.
What is the SwiftUI equivalent for this?
.fileImporter covers the NSOpenPanel case well enough, but I have not found a SwiftUI API that matches the simple NSSavePanel case where the app only needs the URL.
There's a new API in .fileExporter that appears close, but it requires a non nil WritableDocument, and seems designed around SwiftUI performing the file export.
My use case is a macOS app that creates new documents backed by SQLite. SQLite needs a file path so it can create the database at that location. With NSSavePanel, I can ask the user where to save the document, receive a URL, and then create the SQLite database myself.
Is there a SwiftUI API for this on macOS 26 or later? If not, is NSSavePanel still the recommended approach for this case?
It is possible to write databases with SwiftUI.
The API you want to use is the one you mentioned in the original post: https://developer.apple.com/documentation/swiftui/view/fileexporter(ispresented:document:contenttype:defaultfilename:oncompletion:oncancellation:)
Here's the document implementation that allows to write directly to the URL:
final class MyDocument: WritableDocument {
static let writableContentTypes: [UTType] = [.database] // or better, declare a custom UTType for your document type
private var info: MyDatabaseInfo
func writer(configuration: sending WriteConfiguration) -> sending MyWriter {
MyWriter()
}
@MainActor
func snapshot(contentType: UTType) async throws -> sending MyDatabaseInfo { info }
}
struct MyDatabaseInfo { }
struct MyWriter: DocumentWriter {
@concurrent
func write(
snapshot: sending MyDatabaseInfo, to destination: sending URL,
previous: sending MyDatabaseInfo?, progress: consuming Subprogress
) async throws {
// write the database to destination
}
}