Rizwan's Blog πŸ‘¨β€πŸ’»

SwiftUI Import/Export files

July 18, 2020

As discussed on my previous blog post, kickstarting my learnings from contributing to SwiftUI open source project. In this blog post, I try to explain what I have come across very recently which was missed out during WWDC and impressed when I came to know about it. It’s about import and exporting files.

In traditional UIKit, whenever you want to export or import files. We have to rely on UIDocumentPickerViewController. Here is the sample code from NetNewsWire iOS app where we try to export and import OPML files.

Importing files

let docPicker = UIDocumentPickerViewController(documentTypes: opmlUTIs, in: .import)
docPicker.delegate = self
docPicker.modalPresentationStyle = .formSheet
self.present(docPicker, animated: true)

Above code will present a document picker and user can select any OPML files from the Files app.

Exporting files

let docPicker = UIDocumentPickerViewController(url: tempFile, in: .exportToService)
docPicker.modalPresentationStyle = .formSheet
self.present(docPicker, animated: true)

Above code will present a document picker and user can export the OPML files to the Files app.

SwiftUI way

We saw what it takes to import and export files in UIKit. But in SwiftUI all it takes is one environment object.By utilising the all new export and import files environment values we could easily add support to our SwiftUI apps for import/export functions.

Step 1

At first, define the environment object on your View

@Environment(\.exportFiles) var exportAction
@Environment(\.importFiles) var importAction

Step 2

Use the environment variable to export or import files. As like UIKit importing action needs file types and exporting action needs the temporary file urls.

// consider you have file temporary url
exportAction(moving: url) { _ in }
importAction(multipleOfType: types) { (result: Result<[URL], Error>?) in
	if let urls = try? result?.get() {
		// you can do with the file urls here
	}
}

It’s also possible to import/export multiple files.

Check out more on my PR on Github for how it works on NetNewsWire app.

UniformTypeIdenfiers

SwiftUI also comes with a new framework for all UTTypes and it’s called UniformTypeIdentifiers. This also helps us to define what kind of files we can choose from. It comes with predefined files types and you can find all the system declared types here.

For any specific case, we can also create our own UTType with file extensions as well. Here is the code to select only OPML files.

let type = UTType(filenameExtension: "opml")

Links

Check out more info on Apple documentation