I've been struggling with reading the contents of a file, either on-disk or in iCloud, vs. reading contents of a file in the static bundle. I'm getting gummed-up with the correct syntax or function to call to get to a browser to choose the file. Recently, I've tried using fileImporter, and portions of that seem to work, but it also reads the file, and I just want to capture the URL and pass that on to the existing code for reading the information from the static bundle. I had a great session with the Foundations lab this afternoon in WWDC 21, but we ran out of time before we could get to the crux of the matter... I'm not sure I'm providing sufficient clarity with this post, but the apple engineer that I spoke with was very helpful and said he might be able to provide sample code to accomplish this. That would certainly be helpful for me, and maybe others. Thank you!
How to use fileImporter to grab URL for later access to file contents
here is a simple example to get the file url from fileImporter:
@main
struct TestApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
@State var imported = false
@State var fileUrl: URL?
var body: some View {
VStack (spacing: 30) {
Button(action: {imported.toggle()}, label: {
Text("Import file")
})
if let theUrl = fileUrl {
Text("file url is \(theUrl.absoluteString)")
}
}
.fileImporter(isPresented: $imported, allowedContentTypes: [.pdf]) { res in
do {
fileUrl = try res.get()
print("---> fileUrl: \(fileUrl)")
} catch{
print ("error reading: \(error.localizedDescription)")
}
}
}
}