avatar

SwiftUI Import/Export files - Part 2


There were lots of changes this year during the Xcode and iOS beta. Typically we will get major new features on initial beta and subsequent beta will have only bug fixes. This year is a little bit different, we even got changes to Swift UI at the end of the beta cycle.

Beta 6 made a change for SwiftUI import/export files. Instead of environment variable now its a modifier. My previous blog post is outdated and now that Xcode 12 is out, I guess these needs follow up post.

Importing

To import file, we have to use the fileImporter modifier. There is no limit where you have to use this modifier. It’s working same as presenting sheets before.

.fileImporter(
      isPresented: $viewModel.isImporting,
      allowedContentTypes: viewModel.importingContentTypes,
      allowsMultipleSelection: true,
      onCompletion: { result in
        if let urls = try? result.get() {
          // you can do with the file urls here
        }
      }
    )

The parameters were self-explainable. It takes

  • a Binding<Bool> for presented statues
  • an array of content types [UTType]
  • a bool to allow multiple selections while importing
  • a completion block when the import is success

Exporting

To export files, we have to use the fileMover modifier.

.fileMover(isPresented: $viewModel.isExporting,
           file: viewModel.generateExportURL()) { _ in }

File mover takes a Binding<Bool> for presented status and the URL of the file which needs to be exported.

In case, if you would like to know a working example, take a look at this PR I have raised for NetNewsWire app.