How to show save panel in AppKit

Issue #405

Enable Read/Write for User Selected File under Sandbox to avoid bridge absent error

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
func save() {
let panel = NSSavePanel()
// 3
panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser
// 4
panel.nameFieldStringValue = "abc.gif"

// 5
guard let window = view.window else {
return
}

panel.beginSheetModal(for: window) { (result) in
guard result == .OK, let url = panel.url else {
self.showAlert()
return
}
}
}

func showAlert() {
let alert = NSAlert()
alert.messageText = "Hello world"
alert.informativeText = "Information text"
alert.addButton(withTitle: "OK")
alert.addButton(withTitle: "Cancel")
alert.runModal()
}

To save multiple files, use NSOpenPanel

1
2
3
4
5
let panel = NSOpenPanel()
panel.canChooseFiles = false
panel.allowsMultipleSelection = false
panel.canChooseDirectories = true
panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser

Read more

Comments