Dunfey · Hotel WWDC as data, est. 1983
Front desk everything
Years
Topics

2023 App ServicesSystem ServicesSwiftUI & UI Frameworks

WWDC23 · 14 min · App Services / System Services / SwiftUI & UI Frameworks

Build better document-based apps

Discover how you can use the latest features in iPadOS to improve your document-based apps. We’ll show you how to take advantage of UIDocument as well as existing desktop-class iPad and document-based APIs to add new features in your app. Find out how to convert data models to UIDocument, present documents with UIDocumentViewController, learn how to migrate your apps to the latest APIs, and explore best practices.

Watch at developer.apple.com ↗

Transcript all transcripts

Chapters

Code shown on screen · 8 snippets

Loading a document swift · at 3:54 ↗
override func load(fromContents contents: Any, ofType typeName: String?) throws {
    // Load your document from contents
    guard let data = contents as? Data,
          let text = String(data: data, encoding: .utf8) else {
        throw DocumentError.readError
    }
    self.text = text
}
Saving a document swift · at 4:08 ↗
override func contents(forType typeName: String) throws -> Any {
    // Encode your document with an instance of NSData or NSFileWrapper
    guard let data = self.text?.data(using: .utf8) else {
        throw DocumentError.writeError
    }
    return data
}
Manually saving and loading a document swift · at 4:34 ↗
override func save(to url: URL,
                   for saveOperation: UIDocument.SaveOperation,
                   completionHandler: ((Bool) -> Void)? = nil) {
    self.performAsynchronousFileAccess {
        // Set up file coordination and write file to URL
   }
}

override func read(from url: URL) throws {
    // Set up file coordination and read file from URL
}
Defining document that require saving swift · at 5:08 ↗
class Document: UIDocument {
    var text: String? {
        didSet {
            if oldValue != nil && oldValue != text {
                self.updateChangeCount(.done)
            }
        }
    }
}
Updating the view hierarchy for a document swift · at 6:30 ↗
override func documentDidOpen() {
    configureViewForCurrentDocument()
}

override func viewDidLoad() {
    super.viewDidLoad()
    configureViewForCurrentDocument()
}

func configureViewForCurrentDocument() {
    guard let document = markdownDocument,
          !document.documentState.contains(.closed)
            && isViewLoaded else { return }
    // Configure views for document
}
Updating navigation items for a document swift · at 7:17 ↗
override func navigationItemDidUpdate() {
    // Customize navigation item
}
Manually opening a document swift · at 8:01 ↗
documentController.openDocument { success in
    if success {
        self.present(documentController, animated: true)
    }
}
Renaming a UIDocument without UIDocumentViewController swift · at 9:20 ↗
navigationItem.renameDelegate = document

Resources