Implement storage architecture from ai_blueprint.md
Primary sync: replace PersistenceActor JSON file with SwiftData + CloudKit - Add SavedCardModel (@Model class) and PersistenceController (ModelContainer with .automatic CloudKit, fallback to local). BackgroundPersistenceActor (@ModelActor) handles all DB I/O off the main thread. - One-time migration imports user_collection.json into SwiftData and renames the original file to prevent re-import. - Inject modelContainer into SwiftUI environment in IYmtgApp. Image storage: Documents/UserContent/ subfolder (blueprint requirement) - ImageManager.dir now targets iCloud Documents/UserContent/ (or local equiv). - migrateImagesToUserContent() moves existing JPGs to the new subfolder on first launch; called during the SwiftData migration. Firebase: demoted to optional manual backup (metadata only, no images) - Remove all automatic CloudEngine.save/delete/batchUpdatePrices calls from CollectionViewModel mutations. - Add backupAllToFirebase() for user-triggered metadata sync. - Add isFirebaseBackupEnabled to AppConfig (default false). - Add Cloud Backup section in Library settings with iCloud vs Firebase explanation and "Backup Metadata to Firebase Now" button. Also: full modular refactor (Data/, Features/, Services/ directories) and README updated with CloudKit setup steps and revised release checklist. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
137
IYmtg_App_iOS/Data/Persistence/ImageManager.swift
Normal file
137
IYmtg_App_iOS/Data/Persistence/ImageManager.swift
Normal file
@@ -0,0 +1,137 @@
|
||||
import UIKit
|
||||
import Foundation
|
||||
|
||||
// MARK: - IMAGE MANAGER
|
||||
// All card images and user content are stored in a dedicated UserContent/ subfolder
|
||||
// inside either iCloud Drive/Documents/ or the local Documents directory.
|
||||
// This keeps binary files separate from the SwiftData store and aligns with the
|
||||
// blueprint's requirement for a named UserContent container in iCloud Drive.
|
||||
|
||||
class ImageManager {
|
||||
|
||||
// MARK: - Directory Helpers
|
||||
|
||||
/// Active working directory: iCloud Documents/UserContent/ or local Documents/UserContent/.
|
||||
static var dir: URL {
|
||||
let base: URL
|
||||
if FileManager.default.ubiquityIdentityToken != nil,
|
||||
let cloud = FileManager.default.url(forUbiquityContainerIdentifier: nil) {
|
||||
base = cloud.appendingPathComponent("Documents")
|
||||
} else {
|
||||
base = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
|
||||
}
|
||||
let userContent = base.appendingPathComponent("UserContent")
|
||||
if !FileManager.default.fileExists(atPath: userContent.path) {
|
||||
try? FileManager.default.createDirectory(at: userContent, withIntermediateDirectories: true)
|
||||
}
|
||||
return userContent
|
||||
}
|
||||
|
||||
/// The pre-UserContent base directory. Used only for one-time migration; not for new I/O.
|
||||
private static var legacyDir: URL {
|
||||
if FileManager.default.ubiquityIdentityToken != nil,
|
||||
let cloud = FileManager.default.url(forUbiquityContainerIdentifier: nil) {
|
||||
return cloud.appendingPathComponent("Documents")
|
||||
}
|
||||
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
|
||||
}
|
||||
|
||||
// MARK: - Save / Load / Delete
|
||||
|
||||
static func save(_ img: UIImage, name: String) throws {
|
||||
let url = dir.appendingPathComponent(name)
|
||||
|
||||
let maxSize: CGFloat = 1024
|
||||
var actualImg = img
|
||||
if img.size.width > maxSize || img.size.height > maxSize {
|
||||
let scale = maxSize / max(img.size.width, img.size.height)
|
||||
let newSize = CGSize(width: img.size.width * scale, height: img.size.height * scale)
|
||||
let format = UIGraphicsImageRendererFormat()
|
||||
format.scale = 1
|
||||
let renderer = UIGraphicsImageRenderer(size: newSize, format: format)
|
||||
actualImg = renderer.image { _ in img.draw(in: CGRect(origin: .zero, size: newSize)) }
|
||||
}
|
||||
|
||||
guard let data = actualImg.jpegData(compressionQuality: 0.7) else { return }
|
||||
try data.write(to: url, options: .atomic)
|
||||
}
|
||||
|
||||
static func load(name: String) -> UIImage? {
|
||||
let p = dir.appendingPathComponent(name)
|
||||
if FileManager.default.fileExists(atPath: p.path) { return UIImage(contentsOfFile: p.path) }
|
||||
try? FileManager.default.startDownloadingUbiquitousItem(at: p)
|
||||
return UIImage(contentsOfFile: p.path)
|
||||
}
|
||||
|
||||
static func delete(name: String) async {
|
||||
let url = dir.appendingPathComponent(name)
|
||||
try? FileManager.default.removeItem(at: url)
|
||||
}
|
||||
|
||||
// MARK: - Migration
|
||||
|
||||
/// Moves JPG images from the legacy flat directory into the UserContent/ subfolder.
|
||||
/// Called once during the SwiftData migration in BackgroundPersistenceActor.
|
||||
static func migrateImagesToUserContent() {
|
||||
let oldDir = legacyDir
|
||||
let newDir = dir
|
||||
|
||||
guard let files = try? FileManager.default.contentsOfDirectory(
|
||||
at: oldDir, includingPropertiesForKeys: nil
|
||||
) else { return }
|
||||
|
||||
var moved = 0
|
||||
for file in files where file.pathExtension == "jpg" {
|
||||
let dest = newDir.appendingPathComponent(file.lastPathComponent)
|
||||
if !FileManager.default.fileExists(atPath: dest.path) {
|
||||
try? FileManager.default.moveItem(at: file, to: dest)
|
||||
moved += 1
|
||||
}
|
||||
}
|
||||
if moved > 0 { print("MIGRATION: Moved \(moved) images → UserContent/") }
|
||||
}
|
||||
|
||||
/// Legacy: moves images from local Documents to iCloud Documents/UserContent/.
|
||||
/// Retained for compatibility but superseded by migrateImagesToUserContent().
|
||||
static func migrateToCloud() {
|
||||
guard let cloudBase = FileManager.default.url(forUbiquityContainerIdentifier: nil)?
|
||||
.appendingPathComponent("Documents") else { return }
|
||||
let cloudURL = cloudBase.appendingPathComponent("UserContent")
|
||||
let localURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
|
||||
|
||||
if !FileManager.default.fileExists(atPath: cloudURL.path) {
|
||||
try? FileManager.default.createDirectory(at: cloudURL, withIntermediateDirectories: true)
|
||||
}
|
||||
|
||||
guard let files = try? FileManager.default.contentsOfDirectory(
|
||||
at: localURL, includingPropertiesForKeys: nil
|
||||
) else { return }
|
||||
for file in files where file.pathExtension == "jpg" {
|
||||
let dest = cloudURL.appendingPathComponent(file.lastPathComponent)
|
||||
if !FileManager.default.fileExists(atPath: dest.path) {
|
||||
try? FileManager.default.moveItem(at: file, to: dest)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Cleanup
|
||||
|
||||
static func cleanupOrphans(activeImages: Set<String>) {
|
||||
Task.detached {
|
||||
guard !activeImages.isEmpty else { return }
|
||||
let fileManager = FileManager.default
|
||||
guard let files = try? fileManager.contentsOfDirectory(
|
||||
at: dir, includingPropertiesForKeys: [.contentModificationDateKey]
|
||||
) else { return }
|
||||
|
||||
for fileURL in files where fileURL.pathExtension == "jpg" {
|
||||
if !activeImages.contains(fileURL.lastPathComponent),
|
||||
let attrs = try? fileManager.attributesOfItem(atPath: fileURL.path),
|
||||
let date = attrs[.modificationDate] as? Date,
|
||||
Date().timeIntervalSince(date) > 3600 {
|
||||
try? fileManager.removeItem(at: fileURL)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
12
IYmtg_App_iOS/Data/Persistence/PersistenceActor.swift
Normal file
12
IYmtg_App_iOS/Data/Persistence/PersistenceActor.swift
Normal file
@@ -0,0 +1,12 @@
|
||||
import Foundation
|
||||
|
||||
// MARK: - PERSISTENCE ACTOR (Superseded)
|
||||
// This file is kept as a placeholder. The functionality has been replaced by:
|
||||
// - BackgroundPersistenceActor (in Data/Persistence/PersistenceController.swift)
|
||||
// - PersistenceController (in Data/Persistence/PersistenceController.swift)
|
||||
//
|
||||
// The new architecture uses SwiftData with automatic iCloud CloudKit synchronization,
|
||||
// replacing the manual single-file JSON sync. One-time migration from the legacy
|
||||
// user_collection.json is handled in BackgroundPersistenceActor.migrateFromJSONIfNeeded().
|
||||
//
|
||||
// ACTION: Remove this file from the Xcode project navigator once confirmed unused.
|
||||
146
IYmtg_App_iOS/Data/Persistence/PersistenceController.swift
Normal file
146
IYmtg_App_iOS/Data/Persistence/PersistenceController.swift
Normal file
@@ -0,0 +1,146 @@
|
||||
import SwiftData
|
||||
import Foundation
|
||||
|
||||
// MARK: - BACKGROUND PERSISTENCE ACTOR
|
||||
// Performs all SwiftData I/O on a dedicated background context.
|
||||
// CloudKit synchronization is handled automatically by the ModelContainer configuration.
|
||||
// @ModelActor provides a ModelContext bound to this actor's executor (background thread).
|
||||
|
||||
@ModelActor
|
||||
actor BackgroundPersistenceActor {
|
||||
|
||||
// MARK: - Load
|
||||
|
||||
func load() -> [SavedCard] {
|
||||
let descriptor = FetchDescriptor<SavedCardModel>(
|
||||
sortBy: [SortDescriptor(\.dateAdded, order: .reverse)]
|
||||
)
|
||||
let models = (try? modelContext.fetch(descriptor)) ?? []
|
||||
return models.map { $0.toSavedCard() }
|
||||
}
|
||||
|
||||
// MARK: - Save (diff-based to minimise CloudKit writes)
|
||||
|
||||
func save(_ cards: [SavedCard]) {
|
||||
do {
|
||||
let existing = try modelContext.fetch(FetchDescriptor<SavedCardModel>())
|
||||
let existingMap = Dictionary(uniqueKeysWithValues: existing.map { ($0.id, $0) })
|
||||
let incomingIDs = Set(cards.map { $0.id })
|
||||
|
||||
// Delete cards no longer in collection
|
||||
for model in existing where !incomingIDs.contains(model.id) {
|
||||
modelContext.delete(model)
|
||||
}
|
||||
|
||||
// Update existing or insert new
|
||||
for card in cards {
|
||||
if let model = existingMap[card.id] {
|
||||
model.update(from: card)
|
||||
} else {
|
||||
modelContext.insert(SavedCardModel(from: card))
|
||||
}
|
||||
}
|
||||
|
||||
try modelContext.save()
|
||||
} catch {
|
||||
print("BackgroundPersistenceActor save error: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - One-time JSON Migration
|
||||
|
||||
/// Imports cards from the legacy user_collection.json file into SwiftData.
|
||||
/// Runs once on first launch after the SwiftData upgrade; subsequent calls are no-ops.
|
||||
/// Also triggers image migration from the flat Documents/ layout to Documents/UserContent/.
|
||||
func migrateFromJSONIfNeeded() {
|
||||
let migrationKey = "swiftdata_migration_complete_v1"
|
||||
guard !UserDefaults.standard.bool(forKey: migrationKey) else { return }
|
||||
|
||||
let iCloudDocuments = FileManager.default
|
||||
.url(forUbiquityContainerIdentifier: nil)?
|
||||
.appendingPathComponent("Documents")
|
||||
let localDocuments = FileManager.default
|
||||
.urls(for: .documentDirectory, in: .userDomainMask)[0]
|
||||
|
||||
let candidates: [URL] = [
|
||||
iCloudDocuments?.appendingPathComponent("user_collection.json"),
|
||||
localDocuments.appendingPathComponent("user_collection.json")
|
||||
].compactMap { $0 }
|
||||
|
||||
for jsonURL in candidates {
|
||||
guard FileManager.default.fileExists(atPath: jsonURL.path),
|
||||
let data = try? Data(contentsOf: jsonURL),
|
||||
let legacyCards = try? JSONDecoder().decode([SavedCard].self, from: data),
|
||||
!legacyCards.isEmpty else { continue }
|
||||
|
||||
let existingIDs: Set<UUID>
|
||||
do {
|
||||
let existing = try modelContext.fetch(FetchDescriptor<SavedCardModel>())
|
||||
existingIDs = Set(existing.map { $0.id })
|
||||
} catch { existingIDs = [] }
|
||||
|
||||
var imported = 0
|
||||
for card in legacyCards where !existingIDs.contains(card.id) {
|
||||
modelContext.insert(SavedCardModel(from: card))
|
||||
imported += 1
|
||||
}
|
||||
try? modelContext.save()
|
||||
|
||||
// Rename old JSON — keeps it as a fallback without re-triggering import
|
||||
let migratedURL = jsonURL.deletingLastPathComponent()
|
||||
.appendingPathComponent("user_collection.migrated.json")
|
||||
try? FileManager.default.moveItem(at: jsonURL, to: migratedURL)
|
||||
|
||||
print("MIGRATION: Imported \(imported) cards from JSON into SwiftData.")
|
||||
ImageManager.migrateImagesToUserContent()
|
||||
break
|
||||
}
|
||||
|
||||
UserDefaults.standard.set(true, forKey: migrationKey)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - PERSISTENCE CONTROLLER
|
||||
// Owns and provides access to the SwiftData ModelContainer.
|
||||
// The container is configured for automatic iCloud CloudKit synchronization.
|
||||
//
|
||||
// XCODE SETUP REQUIRED (one-time):
|
||||
// 1. Signing & Capabilities → iCloud → enable CloudKit
|
||||
// 2. Add a CloudKit container: "iCloud.<your-bundle-id>"
|
||||
// 3. Signing & Capabilities → Background Modes → enable "Remote notifications"
|
||||
// Without this setup the app runs in local-only mode (no cross-device sync).
|
||||
|
||||
@MainActor
|
||||
final class PersistenceController {
|
||||
static let shared = PersistenceController()
|
||||
|
||||
let container: ModelContainer
|
||||
let backgroundActor: BackgroundPersistenceActor
|
||||
|
||||
private init() {
|
||||
let schema = Schema([SavedCardModel.self])
|
||||
let resolvedContainer: ModelContainer
|
||||
|
||||
do {
|
||||
// .automatic derives the CloudKit container from the app bundle ID.
|
||||
// Degrades gracefully to local storage if iCloud is unavailable.
|
||||
let config = ModelConfiguration(
|
||||
schema: schema,
|
||||
isStoredInMemoryOnly: false,
|
||||
cloudKitDatabase: .automatic
|
||||
)
|
||||
resolvedContainer = try ModelContainer(for: schema, configurations: [config])
|
||||
} catch {
|
||||
print("⚠️ PersistenceController: CloudKit init failed (\(error)). Using local storage.")
|
||||
do {
|
||||
let fallback = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)
|
||||
resolvedContainer = try ModelContainer(for: schema, configurations: [fallback])
|
||||
} catch let fatal {
|
||||
fatalError("PersistenceController: Cannot create ModelContainer. Error: \(fatal)")
|
||||
}
|
||||
}
|
||||
|
||||
self.container = resolvedContainer
|
||||
self.backgroundActor = BackgroundPersistenceActor(modelContainer: resolvedContainer)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user