0

I’m using UIViewControllerRepresentable for Document picker presentation in swiftUI. The issue is that I'm not able to select the video audio pdf it's all showing in a frozen manner. I need to fix this issues for the iOS 14 and above version. I'm able to select the file by tap-hold and then release its only works with the simulator in real devices it’s not possible for both the simulator and devices except for the file structure, the rest of the documents are in greyed out.

enter image description here

struct DocumentPicker: UIViewControllerRepresentable {
    @ObservedObject var chatViewModel: RedesignChatViewModel
    func makeUIViewController(context: UIViewControllerRepresentableContext<DocumentPicker>) -> UIDocumentPickerViewController {
        let viewController = UIDocumentPickerViewController(forOpeningContentTypes: [.pdf, .mp3, .audio, .video, .movie, .item])
        viewController.shouldShowFileExtensions = true
        viewController.allowsMultipleSelection = false
        viewController.delegate = context.coordinator
        return viewController
    }
    func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {
    }
}
extension DocumentPicker {
    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }
    class Coordinator: NSObject, UIDocumentPickerDelegate {
        var parent: DocumentPicker
        var path: String?
        init(_ documentPicker: DocumentPicker) {
            self.parent = documentPicker
        }
        func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
            guard let url = urls.first else { return }
        func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
            controller.dismiss(animated: true)
        }
Aswanth
  • 1
  • 1

1 Answers1

0

There are a few mistakes, first you'll need to create a UIViewController and use that to present the UIDocumentPickerViewController. Also you need to change Coordinator(self) to Coordinator() and in makeUIViewController return context.coordinator.myViewController that should be a lazy property. The reason for this is that self you are passing in is immediately out of date because it is a value type. You also need to remove the @ObservedObject and add lets or @Binding vars for your properties. When the repreresentable is init with new values for those properties, updateUIViewController will be called and you can then update the coordinator and view controller with the new values.

malhal
  • 26,330
  • 7
  • 115
  • 133