János
János

Reputation: 35128

How is it specific use UIDocumentPickerViewController in SwiftUI

Have this code:

struct ContentView: View {
    
    var d1: [String: Any]? = nil
    var res: ValidationResult?
    let documentPicker = UIDocumentPickerViewController(forOpeningContentTypes: [.jpeg, .png])
    documentPicker.delegate = self // <----- HERE
    documentPicker.modalPresentationStyle = .overFullScreen

raise: Expected declaration

Why? What is wrong?

Also how can I start to show document view controller? How to get a reference to a viewcontroller?

Unfortunatelly this crashes:

var body: some View {
    VStack {
        Button(action: {
            documentPicker.present(documentPicker, animated: true)
            
        }){ Text("Load JSON schema").padding() }

I found this for document handling: https://maheshsai252.medium.com/document-handling-in-swiftui-664cf050c724

Strange it does not have body like this:

var body: some View {
    VStack {

why?

Upvotes: 0

Views: 1054

Answers (1)

Tbi
Tbi

Reputation: 316

The problem is that the UIDocumentPickerViewController is only available for UIKit. So you need to create (or better wrap it inside) a UIViewControllerRepresentable in order to use it in SwiftUI. That is what the ProjectDocumentPicker is doing:

ProjectDokumentPicker

You then need to present this ProjectDocumentPicker as a sheet and open it e.g. via button click.

struct ContentView: View {
    @State var showDocumentPicker = false
    @StateObject var reportsVM: ProjectReportViewModel
    @State var added = false
    @State var inCloud = false

        var body: some View {
            Button("Open file") {
                self.showDocumentPicker = true
            }.sheet(
                isPresented: self.$showDocumentPicker,
                content: { ProjectDocumentPicker(reportsViewModel: reportsVM, added: $added, iniCloud: $inCloud) }
            )
        }
    }

Upvotes: 0

Related Questions