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 ↗Chapters
Code shown on screen · 8 snippets
Loading a document
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
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
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
class Document: UIDocument {
var text: String? {
didSet {
if oldValue != nil && oldValue != text {
self.updateChangeCount(.done)
}
}
}
} Updating the view hierarchy for a document
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
override func navigationItemDidUpdate() {
// Customize navigation item
} Manually opening a document
documentController.openDocument { success in
if success {
self.present(documentController, animated: true)
}
} Renaming a UIDocument without UIDocumentViewController
navigationItem.renameDelegate = document Resources
Related sessions
-
31 min -
16 min -
20 min -
13 min -
12 min