WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

How to create a document-based app using FileDocument and DocumentGroup

Paul Hudson    @twostraws   

Updated for Xcode 14.2

SwiftUI comes with support for document-based apps, which are apps that let users create, edit, and share documents such as text files. In SwiftUI we’re given two main types to work with: the FileDocument protocol to define what a document in our app looks like, and the DocumentGroup struct that gives us a default scene to let users create, open, and save documents.

Creating your own document-based app takes four steps:

  1. Defining what your document is, including how it should be saved and loaded.
  2. Creating some sort of view that lets users edit their documents.
  3. Creating a DocumentGroup capable of creating your files and loading them into your user interface.
  4. Updating your Info.plist file to say that you want to use the system’s document browser.

We’ll work through each of those here, starting with defining what your document is. Some document types save multiple files of different types, but for now we’re going to say that we support only plain text, and we want that text to be read and written directly to disk.

First, add import UniformTypeIdentifiers to the top of your Swift file, so you can bring in uniform type identifiers – a fixed way of saying what data types your document can work with.

Now add this struct, defining a simple text file:

struct TextFile: FileDocument {
    // tell the system we support only plain text
    static var readableContentTypes = [UTType.plainText]

    // by default our document is empty
    var text = ""

    // a simple initializer that creates new, empty documents
    init(initialText: String = "") {
        text = initialText
    }

    // this initializer loads data that has been saved previously
    init(configuration: ReadConfiguration) throws {
        if let data = configuration.file.regularFileContents {
            text = String(decoding: data, as: UTF8.self)
        } else {
            throw CocoaError(.fileReadCorruptFile)
        }
    }

    // this will be called when the system wants to write our data to disk
    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
        let data = Data(text.utf8)
        return FileWrapper(regularFileWithContents: data)
    }
}

Notice how in the fileWrapper(configuration:) method we convert our text string into a Data instance, then save that using a FileWrapper. It’s not our job to say where the file should be stored – iOS takes care of that for us.

Our second task is to create some sort of editor area where the user can edit our text. This should use an @Binding property wrapper so that it updates the text in our TextFile struct rather than keeping its own local copy:

struct ContentView: View {
    @Binding var document: TextFile

    var body: some View {
        TextEditor(text: $document.text)
    }
}

Our third step is to edit the main Swift file for the project to include a DocumentGroup, which presents the system-standard interface for browsing, opening, and creating files:

@main
struct YourAwesomeApp: App {
    var body: some Scene {
        DocumentGroup(newDocument: TextFile()) { file in
            ContentView(document: file.$document)
        }
    }
}

As you can see, that tells iOS how to create new files, and also how to show them.

Finally, we need to add a new key to Info.plist, so open that now, right-click in some space, and choose Add Row. For the key name enter “Supports Document Browser”, make sure Type is set to Boolean, then set the value to YES.

The Info.plist file with “Supports Document Browser” set to YES.

That’s it! Your document-based app is ready to go. If you run your app back now you’ll see the standard iOS document picker interface, and if you press + iOS will create a new file and open it for editing in ContentView – nice!

Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Similar solutions…

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.3/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.