Swift • UIDocumentPicker 适用于 iOS 和 iPadOS,但不适用于 Mac Catalyst 版本

时间:2021-05-28 13:25:18

标签: ios swift xcode macos swiftui

我正在为 iPhone 和 iPad 开发 SwiftUI iOS App。该应用程序还利用 Mac Catalyst 将该版本移植到 Mac。

问题:我实现了一个 UIDocumentPicker (UIViewControllerRepresentable),它在 iPhone 和 iPad 上运行良好。在 Mac 上,会出现一个 Finder 窗口,我可以选择一个文件,但是,该文件不会被应用程序处理。

研究:我稍微测试了我的代码并发现,documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) 确实不会Mac Catalyst 版本上被调用,同时被调用iOS / iPadOS 版本。

代码

struct DocumentPicker: UIViewControllerRepresentable {
    @Binding var show: Bool
    
    func makeCoordinator() -> Coordinator {
        return DocumentPicker.Coordinator(documentPicker: self)
    }

    func makeUIViewController(context: Context) -> some UIDocumentPickerViewController {
        let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.pdf], asCopy: true)
        documentPicker.delegate = context.coordinator
        documentPicker.allowsMultipleSelection = false

        return documentPicker
    }

    func updateUIViewController(_ uiViewController: UIViewControllerType, context: UIViewControllerRepresentableContext<DocumentPicker>) {
        // ...
    }

    class Coordinator: NSObject, UIDocumentPickerDelegate {

        var documentPicker: DocumentPicker

        init(documentPicker: DocumentPicker) { self.documentPicker = documentPicker }
        
        func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {

            print("File selected") // Does not get called on macOS.
  
            // Check whether there is a valid URL.
            guard let safeFilePath = urls.first else { return }
       
            // Check whether a File exists at the given URL
            if FileManager.default.fileExists(atPath: safeFilePath.path) {
  
                // Save as Data.
                let data = FileManager.default.contents(atPath: safeFilePath.path)
            }
        }
    }
}

问题:为什么 DocumentPicker 不能在 macOS 上运行,但在 iOS 上运行?

0 个答案:

没有答案
相关问题