Course 1 ยท Chapter 10 ยท Backup, Tests and What Next
The last chapter adds the one feature the spec still lacks, backup: export the whole catalogue to a JSON file and import it back. It then adds tests for the logic worth
protecting, and ends with a roadmap and an honest comparison of this app with the Android one.
What was run, and what was not
Nothing in this chapter was compiled or run (no Mac or Xcode here), and this is the chapter where that matters most, because a backup feature that has never been run is a backup you cannot
trust. My search covered fileExporter with a FileDocument, security-scoped file access for imports, and VisionKit barcode scanning. It found nothing on testing SwiftData
(XCTest, Swift Testing, in-memory containers); that part is from memory. Run the tests in this chapter before relying on any of the rest.
Part 1: The Backup Format
The file deliberately matches the Android app's format, so a backup from one app can be restored in the other: version, exportedAt and items, each item holding its type
by name and its tags as names, and dates as Unix milliseconds (Android's choice; Swift's Date is converted at the edge). A human can read and repair the file.
Unknown extra keys (from a newer version) are ignored by Codable by default, matching the Android setting ignoreUnknownKeys.
Part 2: Export and Import
Three design decisions, mirrored from Android. Import merges and never replaces: an incoming item that matches an existing one on title, creator, type and creation time is skipped,
so importing a file twice does not double the catalogue, while a deliberate second copy (different creation time) survives a round trip. Import is all-or-nothing: validate everything first
(decode, version, every type name), only then insert, and save once. An unknown type is an error, not a guess.
All-or-nothing needs a repository change: the current save(_:tagNames:) inserts and saves each item. Split it into stage(_:tagNames:) (insert, find-or-create tags and assign them:
everything the old function did except the final context.save()) and have save call stage and then save. Import uses stage for every item and saves once.
import Foundation
import SwiftData
structImportResult: Equatable { var added: Int; var skipped: Int }
enumBackupError: LocalizedError {
case newerVersion
case unknownType(String)
var errorDescription: String? {
switchself {
case .newerVersion: return"This backup was made by a newer version of the app."case .unknownType(let t): return"Unknown item type \"\(t)\". This file does not look like a catalogue backup."
}
}
}
@MainActorstructBackupService {
let context: ModelContextfuncexport() throws -> Data {
let items = try context.fetch(FetchDescriptor<Item>(sortBy: [SortDescriptor(\.createdAt)]))
let file = BackupFile(
exportedAt: Date.now.unixMillis,
items: items.map {
BackupItem(title: $0.title, creator: $0.creator, formatDetail: $0.formatDetail,
releaseYear: $0.releaseYear, notes: $0.notes, createdAt: $0.createdAt.unixMillis,
type: $0.typeName, tags: $0.sortedTags.map(\.name))
}
)
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
return try encoder.encode(file)
}
funcimportBackup(_ data: Data) throws -> ImportResult {
// 1. Validate everything before touching the store.let file = tryJSONDecoder().decode(BackupFile.self, from: data)
guard file.version <= BackupFile.currentVersion else { throwBackupError.newerVersion }
let repo = CatalogueRepository(context: context)
try repo.ensureSeeded()
let types = Dictionary(uniqueKeysWithValues: try repo.itemTypes().map { ($0.name.lowercased(), $0) })
for b in file.items where types[b.type.lowercased()] == nil {
throwBackupError.unknownType(b.type)
}
// 2. Existing items, as a set of exact-match signatures.funcsignature(_ title: String, _ creator: String, _ type: String, _ created: Int64) -> String {
"\(title)\u{1F}\(creator)\u{1F}\(type.lowercased())\u{1F}\(created)"
}
var existing = Set(try context.fetch(FetchDescriptor<Item>()).map {
signature($0.title, $0.creator, $0.typeName, $0.createdAt.unixMillis)
})
// 3. Stage every new item, then save once.var added = 0, skipped = 0
for b in file.items {
let title = b.title.trimmingCharacters(in: .whitespacesAndNewlines)
let creator = b.creator.trimmingCharacters(in: .whitespacesAndNewlines)
let sig = signature(title, creator, b.type, b.createdAt)
if title.isEmpty || existing.contains(sig) { skipped += 1; continue }
let item = Item(title: title, creator: creator, type: types[b.type.lowercased()]!)
item.formatDetail = b.formatDetail.trimmingCharacters(in: .whitespacesAndNewlines)
item.releaseYear = b.releaseYear
item.notes = b.notes.trimmingCharacters(in: .whitespacesAndNewlines)
item.createdAt = Date(unixMillis: b.createdAt)
try repo.stage(item, tagNames: b.tags)
existing.insert(sig)
added += 1
}
do {
try context.save()
} catch {
context.rollback() // nothing half-importedthrow error
}
returnImportResult(added: added, skipped: skipped)
}
}
I assumed Item(title:creator:type:) and the repository helpers keep their earlier shapes; adapt the calls to your files. context.rollback() is how I believe unsaved changes are
discarded; it is from memory and untested. The unit-separator character in the signature keeps "AB"+"C" from colliding with "A"+"BC". Note that the signature uses the item's exact title and creator
where the duplicate warning folds case: an import should skip only a true copy.
Part 3: The Screen
A FileDocument wraps the bytes for the exporter. The sources show the pattern: a struct that supplies the data to write and, for a document type you also read, a way to read it back. Here the
document is write-only, so it only needs to supply data:
import SwiftUI
import UniformTypeIdentifiers
structBackupDocument: FileDocument {
static var readableContentTypes: [UTType] { [.json] }
var data: Datainit(data: Data) { self.data = data }
init(configuration: ReadConfiguration) throws {
guard let bytes = configuration.file.regularFileContents else { throwCocoaError(.fileReadCorruptFile) }
data = bytes
}
funcfileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
FileWrapper(regularFileWithContents: data)
}
}
structBackupView: View {
@Environment(\.modelContext)private var context
@Environment(\.dismiss)private var dismiss
@Environment(ErrorCenter.self)private var errors
@Stateprivate var exportDocument: BackupDocument?
@Stateprivate var showExporter = false@Stateprivate var showImporter = false@Stateprivate var resultText: String?
var body: someView {
NavigationStack {
Form {
Section {
Button("Export backup...", systemImage: "square.and.arrow.up") { prepareExport() }
} footer: { Text("Saves every item as a JSON file you choose where to keep.") }
Section {
Button("Import backup...", systemImage: "square.and.arrow.down") { showImporter = true }
} footer: { Text("Adds items from a backup. Existing items are never changed or removed.") }
}
.navigationTitle("Backup")
.navigationBarTitleDisplayMode(.inline)
.toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }
.fileExporter(isPresented: $showExporter, document: exportDocument, contentType: .json,
defaultFilename: "catalogue-backup") { result inif case .failure(let error) = result { errors.report(error, doing: "export the backup") }
else { resultText = "Backup saved." }
}
.fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result inhandleImport(result)
}
.alert("Backup", isPresented: Binding(get: { resultText != nil }, set: { if !$0 { resultText = nil } })) {
Button("OK", role: .cancel) { }
} message: { Text(resultText ?? "") }
}
}
private funcprepareExport() {
do {
exportDocument = BackupDocument(data: tryBackupService(context: context).export())
showExporter = true// both the document and the flag are needed before the picker shows
} catch {
errors.report(error, doing: "prepare the backup")
}
}
private funchandleImport(_ result: Result<URL, Error>) {
do {
let url = try result.get()
let scoped = url.startAccessingSecurityScopedResource()
defer { if scoped { url.stopAccessingSecurityScopedResource() } }
let data = tryData(contentsOf: url)
let outcome = tryBackupService(context: context).importBackup(data)
resultText = "Added \(outcome.added) item(s), skipped \(outcome.skipped) already present."
} catch {
errors.report(error, doing: "import the backup")
}
}
}
Why the security-scope calls: the sources say that a file chosen outside the app's own container cannot be read unless the URL's security scope is opened first, bracketed by start... and
stop... with a defer; calling them on an in-container file is harmless. Reading happens inside the bracket, which is the whole point. Present BackupView as a sheet from a
new toolbar button on ListView (for example a Menu with a "Backup" entry and the externaldrive symbol).
Part 4: Tests
Test the code that decides things, not the screens. Everything below is plain Swift or an in-memory container (Persistence.makeContainer(inMemory: true), built in Chapter 3 for exactly
this), so the tests run in milliseconds and touch no real data. I use XCTest because it exists in every Xcode; Apple's newer Swift Testing library (import Testing, @Test,
#expect) is the alternative, and I did not verify either in my search.
import XCTest
import SwiftData
@testableimport Catalogue // your app target's module name@MainActorfinal classCatalogueTests: XCTestCase {
private funcmakeContext() throws -> ModelContext {
let container = tryPersistence.makeContainer(inMemory: true)
let context = container.mainContext
tryCatalogueRepository(context: context).ensureSeeded()
return context
}
// ---- the draft: plain Swift, no database ----functestBlankTitleIsInvalid() {
var d = ItemDraft(); d.typeName = "Book"; d.title = " "XCTAssertTrue(d.titleError)
XCTAssertFalse(d.isValid)
}
functestYearRules() {
var d = ItemDraft(); d.typeName = "Book"; d.title = "Dune"
d.yearText = ""; XCTAssertFalse(d.yearError) // optional
d.yearText = "1965"; XCTAssertFalse(d.yearError)
d.yearText = "999"; XCTAssertTrue(d.yearError)
d.yearText = "abcd"; XCTAssertTrue(d.yearError)
}
// ---- the repository, in memory ----functestTagsAreCaseInsensitiveAndShared() throws {
let context = trymakeContext()
let repo = CatalogueRepository(context: context)
let type = try repo.itemTypes()[0]
try repo.save(Item(title: "Dune", creator: "", type: type), tagNames: ["Sci-Fi"])
try repo.save(Item(title: "Alien", creator: "", type: type), tagNames: ["sci-fi"])
XCTAssertEqual(try context.fetch(FetchDescriptor<Tag>()).count, 1)
}
// ---- backup ----functestRoundTripAndMerge() throws {
let source = trymakeContext()
let type = tryCatalogueRepository(context: source).itemTypes()[0]
tryCatalogueRepository(context: source).save(Item(title: "Dune", creator: "Frank Herbert", type: type), tagNames: ["classic"])
let data = tryBackupService(context: source).export()
let target = trymakeContext()
XCTAssertEqual(tryBackupService(context: target).importBackup(data), ImportResult(added: 1, skipped: 0))
XCTAssertEqual(tryBackupService(context: target).importBackup(data), ImportResult(added: 0, skipped: 1)) // idempotent
}
functestUnknownTypeChangesNothing() throws {
let context = trymakeContext()
let json = #"{"version":1,"exportedAt":0,"items":[{"title":"X","createdAt":1,"type":"Cassette"}]}"#XCTAssertThrowsError(tryBackupService(context: context).importBackup(Data(json.utf8)))
XCTAssertEqual(try context.fetch(FetchDescriptor<Item>()).count, 0)
}
}
Two of these tests exercise things I flagged as unverified in earlier chapters (a find-before-insert on a unique key, and a clean import). If one fails, it has done its job: read the failure before
changing the test. A test that you edit until it passes proves nothing.
Part 5: What Next, and Android Compared
Barcode scanning is the natural next feature: scan an ISBN or UPC and pre-fill the title. The sources describe VisionKit's DataScannerViewController: it is a UIKit view
controller, so SwiftUI hosts it through a UIViewControllerRepresentable; you restrict it to barcode symbologies such as EAN-13 (retail codes); it needs camera permission; and you should check
isSupported and isAvailable before showing it. Turning a code into a title needs a lookup service (the open Open Library API for books, for example), and that is a network feature
this offline app has so far avoided, so the privacy and failure behaviour must be designed first. Other ideas: cover images, a Home Screen widget, and iCloud sync. Caution on sync, from memory only:
I recall that CloudKit-backed SwiftData does not allow unique constraints, which Chapter 2's tag key uses; verify before planning it.
Concern
Android course
iOS course
Database
Room, explicit cross-reference table, RESTRICT
SwiftData, implicit join, .deny
Case-insensitive tags
NOCASE (ASCII only) + normalised column
Folded key (case and diacritics)
Live data to screen
Flow, ViewModel, StateFlow
@Query, @Observable
Navigation
Type-safe routes passing an id
NavigationStack passing the object
Form
State in a ViewModel
Draft struct in @State
Search
debounce + flatMapLatest
.searchable + re-initialised @Query
Backup
Storage Access Framework, same JSON
fileExporter / fileImporter, same JSON
Dependency injection
Hilt
The environment (modelContext, ErrorCenter)
Biggest risk
Boilerplate and wiring
Less control: model lifetimes and re-fetch timing
Compare with the Android course
Personal Catalogue: Android (Kotlin & Compose) Chapter 10 ended with the same three parts: backup, tests, roadmap. The two apps now share a data model, a set of rules and a backup file, which was the
purpose of building them as a pair. The honest summary: Android makes you assemble more, and you can see every piece; SwiftUI and SwiftData assemble more for you, and the problems that remain (deleting a model
a screen still holds, predicates that crash, re-fetch timing) appear at runtime rather than as code you wrote. The Android course also ran its tests with a build tool I could not run here. Neither course's code
was compiled, so the first job for either app is to open it in its IDE, build it, and fix what the compiler finds.
Challenges
Exercise 1
Split the repository's save into stage and save, add the backup files, BackupView and the toolbar entry. Export a catalogue of at least
three items, open the file in a text editor and describe its structure, then import it into a fresh install and note the result message.
Add the test file and run it. For each test that fails, report the failure message and whether the fault is in the code or in a wrong assumption of mine. Then add one test of your own for the
ListViewModel type-and-tag filter.
Cross-platform check: export from the iOS app and import into the Android app (or the reverse), using a catalogue with a diacritic in a title and a tag. Record what survives, what is skipped,
and anything the two formats disagree on.
Backup file: {version, exportedAt, items[{title, creator, formatDetail, releaseYear, notes, createdAt (Unix ms), type (name), tags (names)}]}, shared with the Android app
Export: a FileDocument holding the bytes, .fileExporter(isPresented:document:contentType:defaultFilename:); the document and the flag must both be set
Import: .fileImporter(isPresented:allowedContentTypes:), bracket the read with startAccessingSecurityScopedResource() / stop... in a defer
Merge, never replace; skip exact matches (title, creator, type, creation time); validate everything first, stage all, save once, roll back on failure
Tests: in-memory container, plain-Swift draft and view-model tests; read failures before editing tests
Roadmap: VisionKit DataScannerViewController (check isSupported and isAvailable), cover images, widget, sync (check the unique-key limitation)
Not Yet Verified
Checked (searches on 2026-11-19, tutorials and forum posts): that fileExporter takes a presentation binding and an optional document (both needed before the picker appears) and that
a FileDocument wrapping data is the usual pattern; that .json is a standard import type; that files outside the app container need the security scope started and stopped, with calls on
in-container files harmless; that a SwiftUI app hosts VisionKit's DataScannerViewController through a representable, restricts it to barcode symbologies, needs camera permission, and should check
isSupported and isAvailable. Not checked, from general knowledge: everything about testing SwiftData (the search found nothing): XCTest versus Swift Testing, @MainActor test classes, the
@testable import module name, and in-memory containers in tests; context.rollback() discarding the staged inserts; the stage split of the repository, which depends on
code from earlier chapters I am only recalling; the fileExporter completion-closure form used here (there are several overloads); that CloudKit-backed SwiftData forbids unique constraints; the
Open Library suggestion; and all code, none of which was compiled or run, including the tests. I did not consult Apple's reference pages.
That is the last chapter of Personal Catalogue: iOS (Swift & SwiftUI). The honest status: the design and the code are written, researched where my searches could reach, and
entirely unbuilt. Open a new Xcode project, work through the chapters in order, and treat every compiler error and failing test as information about this course. Its Android counterpart,
Personal Catalogue: Android (Kotlin & Compose), shares the data model and the backup file.