I am developing an SwiftUI iOS App
for iPhone & iPad. The App also utilizes Mac Catalyst
to port the Version to the Mac.
Problem: I implemented a UIDocumentPicker (UIViewControllerRepresentable) which works great on iPhone & iPad. On the Mac, a Finder-Window appears and I can select a File, however, the file does not get processed by the app then.
Research: I tested my code a bit and discovered, that documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL])
does not get called on the Mac Catalyst
Version, while getting called on the iOS / iPadOS
Version.
Code
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)
}
}
}
}
Question: Why does the DocumentPicker
not work on macOS
but on iOS?