geethsg7
geethsg7

Reputation: 295

How do I save an imported file name as string after importing file in SwiftUI?

I am trying import a JSON file onto my app and I trying to read the name so that I can use that string to display the JSON onto my app. I have the file importer working but I need help on saving that name of the file as a String.

import SwiftUI

struct ContentView: View {
    @State var imported = false
    
    var body: some View {
        VStack{
            
            Button(action: {imported.toggle()}, label: {
                Text("Import")
            })
        }
        
        .fileImporter(isPresented: $imported, allowedContentTypes: [.json]) { (res) in

        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

Upvotes: 0

Views: 800

Answers (1)

try something like this:

struct ContentView: View {
    @State var imported = false
    @State var fileName = ""
    
    var body: some View {
        VStack (spacing: 30) {
            Button(action: {imported.toggle()}, label: {
                Text("Import")
            })
            Text("file selected is \(fileName)")  // <--- the file name you selected
        }
        .fileImporter(isPresented: $imported, allowedContentTypes: [.json]) { res in
            do {
                let fileUrl = try res.get()
                self.fileName = fileUrl.lastPathComponent  // <--- the file name you want

                let fileData = try Data(contentsOf: fileUrl)
                // try! JSONDecoder().decode([YourObject].self, from: fileData)

            } catch{
                print ("error reading: \(error.localizedDescription)")
            }
        }
    }
}

Upvotes: 1

Related Questions