2

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?

christophriepe
  • 1,157
  • 12
  • 47
  • have you check? : https://stackoverflow.com/a/62225520/14733292 – Raja Kishan May 28 '21 at 13:30
  • @RajaKishan thanks for your answer, but I already found this question and it didn't help. In my case, the document picker does appear, however, the `didPickDocumentsAt` delegate-method does not get called on macOS – christophriepe May 28 '21 at 16:31

1 Answers1

2

When you create UIDocumentPickerViewController, use asCopy: false.

noe
  • 1,684
  • 1
  • 17
  • 35