iosswiftswiftuiswift3swiftui-form

File importer/ File Mover methods are not getting invoked when using Form swift UI


even though the binding properties in fileMover are set to true. file mover is not getting executed. Below is the sample code i have used. Any leads will be helpful. Thanks in advance.

var body: SomeView {
    
    Form {
        Section {
            HStack {
                //some view logic
            }.fileMover(isPresented: $viewModel.shouldStartFileExport,
                        file: viewModel.targetURL) { result in
                print("result")
            }
        }
    }
}
struct ViewModel {
    @State var shouldStartFileExport = false
    @State var targetURL: URL = //some URL
}

Solution

  • You should not use "@State" inside "struct ViewModel" like you did, they are for views.

    There are many ways to have your variables changing, here I show you can use "ObservableObject", or you can simply use "@State" in the view.

        class ViewModel: ObservableObject {
            @Published var shouldStartFileExport = false
            @Published var targetURL = URL(string: "somefileurl")!
        }
        
        struct ContentView: View {
        //    @State var shouldStartFileExport = false
        //    @State var targetURL = URL(string: "somefileurl")!
        @StateObject var viewModel = ViewModel()
        
        var body: some View {
            Form {
                Section {
                    HStack {
                        Button("fileMover test") { viewModel.shouldStartFileExport = true }
                    }
                }
            }
            .fileMover(isPresented: $viewModel.shouldStartFileExport, file: viewModel.targetURL) { result in
                print("\n-----> result <-----\n")
            }
        }
        
    }