How to open file dialog with SwiftUI on platform “UIKit for Mac”?

耗尽温柔 提交于 2020-11-30 12:34:48

问题


NSOpenPanel is not available on platform "UIKit for Mac": https://developer.apple.com/documentation/appkit/nsopenpanel

If Apple doesn't provide a built-in way, I guess someone will create a library based on SwiftUI and FileManager that shows the dialog to select files.


回答1:


Here's a solution to select a file for macOS with Catalyst & UIKit

In your swiftUI view :

Button("Choose file") {
    let picker = DocumentPickerViewController(
        supportedTypes: ["log"], 
        onPick: { url in
            print("url : \(url)")
        }, 
        onDismiss: {
            print("dismiss")
        }
    )
    UIApplication.shared.windows.first?.rootViewController?.present(picker, animated: true)
}

The DocumentPickerViewController class :

class DocumentPickerViewController: UIDocumentPickerViewController {
    private let onDismiss: () -> Void
    private let onPick: (URL) -> ()

    init(supportedTypes: [String], onPick: @escaping (URL) -> Void, onDismiss: @escaping () -> Void) {
        self.onDismiss = onDismiss
        self.onPick = onPick

        super.init(documentTypes: supportedTypes, in: .open)

        allowsMultipleSelection = false
        delegate = self
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension DocumentPickerViewController: UIDocumentPickerDelegate {
    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
        onPick(urls.first!)
    }

    func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
        onDismiss()
    }
}



回答2:


Both UIDocumentPickerViewController and UIDocumentBrowserViewController work in Catalyst. Use them exactly as you would on iOS and they will “magically” appear as standard Mac open/save dialogs.

Nice example here if you need it: https://appventure.me/guides/catalyst/how/open_save_export_import.html



来源:https://stackoverflow.com/questions/56645819/how-to-open-file-dialog-with-swiftui-on-platform-uikit-for-mac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!