【问题标题】:How do I allow users to save a file to a specific directory and specify a file name in a macOS app?如何允许用户将文件保存到特定目录并在 macOS 应用程序中指定文件名?
【发布时间】:2020-11-03 23:05:08
【问题描述】:

我在 Swift 中构建了一个 iOS 应用,我正在为 macOS Catalyst 添加一些功能。

在我的应用程序中,我在单击按钮时创建了一个 .txt 文件。我想提供一个UIDocumentPickerViewController,它允许用户指定保存目录和文件名。到目前为止,我只能显示UIDocumentPickerViewController,而没有命名文件或保存的选项。 UIDocumentPickerViewController 是完成此任务的正确视图控制器吗?如果是,如何指定保存目录和文件名?

这是我用来展示UIDocumentPickerViewController的代码

#if targetEnvironment(macCatalyst)
            
            let str = "Hello boxcutter"
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] as NSURL
            let fileURL = documentsURL.appendingPathComponent("boxCutter.txt")
            try! str.write(to: fileURL!, atomically: true, encoding: String.Encoding.utf8)
            
            let types: [String] = [kUTTypeFolder as String]
            let documentPicker = UIDocumentPickerViewController(documentTypes: types, in: .open)
            documentPicker.delegate = self
            documentPicker.allowsMultipleSelection = false
            documentPicker.modalPresentationStyle = .formSheet
            self.present(documentPicker, animated: true, completion: nil)

#endif

【问题讨论】:

  • UIDocumentPickerViewController 通常用于导入/打开文件。您应该首先将其保存在本地,然后使用UIDocumentIteractionController 允许用户共享本地文件,但我从未使用 Catalyst 测试过。 stackoverflow.com/questions/46456481/…

标签: swift macos uidocumentpickerviewcontroller


【解决方案1】:

您可以使用NSSavePanel 询问用户将文件保存在哪里。这是一个无法从 Catalyst 应用程序直接访问的 macOS API,但您可以创建一个可以访问 macOS API 的 macOS 插件,如 here 所述。或者使用像Dynamic这样的库(完全披露:我是作者)在没有插件的情况下实现同样的事情:

let nsWindow = Dynamic.NSApplication.sharedApplication.delegate.hostWindowForUIWindow(view.window)

let panel = Dynamic.NSSavePanel()
panel.nameFieldStringValue = "boxCutter.txt"
panel.beginSheetModalForWindow(nsWindow, completionHandler: { response in
    if response == 1 /*OK*/ {
        print("file URL: ", panel.URL.asURL)
    }
} as ResponseBlock)

typealias ResponseBlock = @convention(block) (_ response: Int) -> Void

【讨论】:

    猜你喜欢
    • 2013-11-17
    • 2016-12-17
    • 2022-12-15
    • 1970-01-01
    • 1970-01-01
    • 2011-04-28
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    相关资源
    最近更新 更多