import Foundation import SwiftData @Model final class ServerRecord { var origin = "" var saved = Date.distantPast var color = 0 init(origin: String, color: Int) { self.origin = origin self.color = color saved = Date() } } @Model final class DraftRecord { var scope = "" var json = Data() var saved = Date.distantPast init(scope: String, json: Data) { self.scope = scope self.json = json saved = Date() } } @Model final class VisitRecord { var taskId = "" var at = 0.0 init(taskId: String, at: Double) { self.taskId = taskId self.at = at } } private let container: ModelContainer = { let schema = Schema([ServerRecord.self, DraftRecord.self, VisitRecord.self]) let dir = URL.applicationSupportDirectory.appending(path: "run.fc.byre.mac", directoryHint: .isDirectory) do { try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) return try ModelContainer(for: schema, configurations: ModelConfiguration(schema: schema, url: dir.appending(path: "byre.store"), cloudKitDatabase: .private("iCloud.run.fc.byre.mac"))) } catch { fatalError("open persistent store: \(error)") } }() @MainActor var persistence: ModelContext { container.mainContext } @MainActor func fetchRecords(_ descriptor: FetchDescriptor) -> [T] { do { return try persistence.fetch(descriptor) } catch { log.error("fetch \(String(describing: T.self), privacy: .public): \(String(describing: error), privacy: .public)") return [] } } @MainActor func saveRecords() { do { try persistence.save() } catch { log.error("save records: \(String(describing: error), privacy: .public)") } }