Backup, Tests and Next Steps

Personal Catalogue: iOS (Swift & SwiftUI)

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.

import Foundation struct BackupFile: Codable { static let currentVersion = 1 var version = BackupFile.currentVersion var exportedAt: Int64 var items: [BackupItem] } struct BackupItem: Codable { var title: String var creator = "" var formatDetail = "" var releaseYear: Int? var notes = "" var createdAt: Int64 var type: String var tags: [String] = [] init(title: String, creator: String = "", formatDetail: String = "", releaseYear: Int? = nil, notes: String = "", createdAt: Int64, type: String, tags: [String] = []) { self.title = title; self.creator = creator; self.formatDetail = formatDetail self.releaseYear = releaseYear; self.notes = notes self.createdAt = createdAt; self.type = type; self.tags = tags } // Swift's synthesised decoding rejects a missing key; hand-written, so absent optional fields are tolerated. init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) title = try c.decode(String.self, forKey: .title) creator = try c.decodeIfPresent(String.self, forKey: .creator) ?? "" formatDetail = try c.decodeIfPresent(String.self, forKey: .formatDetail) ?? "" releaseYear = try c.decodeIfPresent(Int.self, forKey: .releaseYear) notes = try c.decodeIfPresent(String.self, forKey: .notes) ?? "" createdAt = try c.decode(Int64.self, forKey: .createdAt) type = try c.decode(String.self, forKey: .type) tags = try c.decodeIfPresent([String].self, forKey: .tags) ?? [] } } extension Date { var unixMillis: Int64 { Int64((timeIntervalSince1970 * 1000).rounded()) } init(unixMillis: Int64) { self.init(timeIntervalSince1970: Double(unixMillis) / 1000) } }

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 struct ImportResult: Equatable { var added: Int; var skipped: Int } enum BackupError: LocalizedError { case newerVersion case unknownType(String) var errorDescription: String? { switch self { 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." } } } @MainActor struct BackupService { let context: ModelContext func export() 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) } func importBackup(_ data: Data) throws -> ImportResult { // 1. Validate everything before touching the store. let file = try JSONDecoder().decode(BackupFile.self, from: data) guard file.version <= BackupFile.currentVersion else { throw BackupError.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 { throw BackupError.unknownType(b.type) } // 2. Existing items, as a set of exact-match signatures. func signature(_ 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-imported throw error } return ImportResult(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 struct BackupDocument: FileDocument { static var readableContentTypes: [UTType] { [.json] } var data: Data init(data: Data) { self.data = data } init(configuration: ReadConfiguration) throws { guard let bytes = configuration.file.regularFileContents else { throw CocoaError(.fileReadCorruptFile) } data = bytes } func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { FileWrapper(regularFileWithContents: data) } } struct BackupView: View { @Environment(\.modelContext) private var context @Environment(\.dismiss) private var dismiss @Environment(ErrorCenter.self) private var errors @State private var exportDocument: BackupDocument? @State private var showExporter = false @State private var showImporter = false @State private var resultText: String? var body: some View { 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 in if case .failure(let error) = result { errors.report(error, doing: "export the backup") } else { resultText = "Backup saved." } } .fileImporter(isPresented: $showImporter, allowedContentTypes: [.json]) { result in handleImport(result) } .alert("Backup", isPresented: Binding(get: { resultText != nil }, set: { if !$0 { resultText = nil } })) { Button("OK", role: .cancel) { } } message: { Text(resultText ?? "") } } } private func prepareExport() { do { exportDocument = BackupDocument(data: try BackupService(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 func handleImport(_ result: Result<URL, Error>) { do { let url = try result.get() let scoped = url.startAccessingSecurityScopedResource() defer { if scoped { url.stopAccessingSecurityScopedResource() } } let data = try Data(contentsOf: url) let outcome = try BackupService(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 @testable import Catalogue // your app target's module name @MainActor final class CatalogueTests: XCTestCase { private func makeContext() throws -> ModelContext { let container = try Persistence.makeContainer(inMemory: true) let context = container.mainContext try CatalogueRepository(context: context).ensureSeeded() return context } // ---- the draft: plain Swift, no database ---- func testBlankTitleIsInvalid() { var d = ItemDraft(); d.typeName = "Book"; d.title = " " XCTAssertTrue(d.titleError) XCTAssertFalse(d.isValid) } func testYearRules() { 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 ---- func testTagsAreCaseInsensitiveAndShared() throws { let context = try makeContext() 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 ---- func testRoundTripAndMerge() throws { let source = try makeContext() let type = try CatalogueRepository(context: source).itemTypes()[0] try CatalogueRepository(context: source).save(Item(title: "Dune", creator: "Frank Herbert", type: type), tagNames: ["classic"]) let data = try BackupService(context: source).export() let target = try makeContext() XCTAssertEqual(try BackupService(context: target).importBackup(data), ImportResult(added: 1, skipped: 0)) XCTAssertEqual(try BackupService(context: target).importBackup(data), ImportResult(added: 0, skipped: 1)) // idempotent } func testUnknownTypeChangesNothing() throws { let context = try makeContext() let json = #"{"version":1,"exportedAt":0,"items":[{"title":"X","createdAt":1,"type":"Cassette"}]}"# XCTAssertThrowsError(try BackupService(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.

ConcernAndroid courseiOS course
DatabaseRoom, explicit cross-reference table, RESTRICTSwiftData, implicit join, .deny
Case-insensitive tagsNOCASE (ASCII only) + normalised columnFolded key (case and diacritics)
Live data to screenFlow, ViewModel, StateFlow@Query, @Observable
NavigationType-safe routes passing an idNavigationStack passing the object
FormState in a ViewModelDraft struct in @State
Searchdebounce + flatMapLatest.searchable + re-initialised @Query
BackupStorage Access Framework, same JSONfileExporter / fileImporter, same JSON
Dependency injectionHiltThe environment (modelContext, ErrorCenter)
Biggest riskBoilerplate and wiringLess 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.

๐Ÿ“„ View solution
Exercise 2

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.

๐Ÿ“„ View solution
Exercise 3

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.

๐Ÿ“„ View solution

Chapter 10 Quick Reference

  • 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.
Course complete
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.