Following this: https://capps.tech/blog/read-files-with-documentpicker-in-swiftui
and this: https://gist.github.com/MentalN/d4d2647aedd761831eeaf1450c299887
After file selection in dialog happend, this method get called:
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
parent.filePath = urls[0]
print(urls[0].absoluteString)
}
Instead of print filepath, can I pass it to SwiftUI? How?
This methos is inside: Coordinator class, and that is inside DocumentPicker.
import SwiftUI
struct DocumentPicker: UIViewControllerRepresentable {
@Binding var filePath: URL?
func makeCoordinator() -> DocumentPicker.Coordinator {
return DocumentPicker.Coordinator(parent1: self)
}
func makeUIViewController(context: UIViewControllerRepresentableContext<DocumentPicker>) -> UIDocumentPickerViewController {
let picker = UIDocumentPickerViewController(documentTypes: ["public.item"], in: .open)
picker.allowsMultipleSelection = false
picker.delegate = context.coordinator
return picker
}
func updateUIViewController(_ uiViewController: DocumentPicker.UIViewControllerType, context: UIViewControllerRepresentableContext<DocumentPicker>) {
}
class Coordinator: NSObject, UIDocumentPickerDelegate {
var parent: DocumentPicker
init(parent1: DocumentPicker){
parent = parent1
}
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
parent.filePath = urls[0]
print(urls[0].absoluteString)
}
}
}
In SwiftUI part there is a button in body:
var body: some View {
VStack {
Button(action: {
showDocumentPicker = true
}){ Text("Load JSON schema").padding() }
it switch a flag.
@State private var showDocumentPicker = false
then sheet get caled:
}.sheet(isPresented: self.$showDocumentPicker) {
DocumentPicker(filePath: $fileContent)
}
I tried to add fileContent to the body but got a compiler error:
Text("\(self.fileContent)").padding()
No exact matches in call to instance method 'appendInterpolation'