swiftui

Select directory in SwiftUI file importer


I want to show a file importer that allows to select both regular files as well as directories. When running the following code on iOS, I can tap a PDF file and the file importer closes as expected, but when tapping a directory, the file importer shows its contents. How can I instead select that directory and close the file importer? The navigation bar shows a Cancel button, but no Open button.

enter image description here

struct FileView: View {
    @State private var showFileImporter = false

    var body: some View {
        ScrollView {
            VStack(alignment: .leading) {
                VStack(alignment: .center) {
                    Button("Open") {
                        showFileImporter = true
                    }
                }
            }
        }
        .fileImporter(isPresented: $showFileImporter, allowedContentTypes: [.pdf, .directory], onCompletion: { result in
            // TODO
        })
    }

}

Solution

  • Almost there, change allowed content types to

    allowedContentTypes: [.pdf, .folder]
    

    I couldn't clearly understand from the documentation why folder works but not directory but perhaps they mean that a folder is a user element but a directory is at the OS level