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:
109
IYmtg_App_iOS/Data/Models/Card.swift
Normal file
109
IYmtg_App_iOS/Data/Models/Card.swift
Normal file
@@ -0,0 +1,109 @@
|
||||
import Foundation
|
||||
|
||||
struct CardFingerprint: Codable, Identifiable, Sendable {
|
||||
let id: UUID
|
||||
let name: String
|
||||
let setCode: String
|
||||
let collectorNumber: String
|
||||
let hasFoilPrinting: Bool
|
||||
let hasSerializedPrinting: Bool?
|
||||
let featureData: Data
|
||||
var priceScanned: Double? = nil
|
||||
}
|
||||
|
||||
struct CardMetadata: Identifiable, Sendable {
|
||||
let id: UUID
|
||||
let name: String
|
||||
let setCode: String
|
||||
let collectorNumber: String
|
||||
let hasFoilPrinting: Bool
|
||||
let hasSerializedPrinting: Bool
|
||||
var priceScanned: Double? = nil
|
||||
var rarity: String? = nil
|
||||
var colorIdentity: [String]? = nil
|
||||
var isSerialized: Bool = false
|
||||
}
|
||||
|
||||
struct SavedCard: Codable, Identifiable, Hashable, Sendable {
|
||||
let id: UUID
|
||||
let scryfallID: String
|
||||
var name: String
|
||||
var setCode: String
|
||||
var collectorNumber: String
|
||||
let imageFileName: String
|
||||
var condition: String
|
||||
var foilType: String
|
||||
var currentValuation: Double?
|
||||
var previousValuation: Double?
|
||||
var dateAdded: Date
|
||||
var classification: String
|
||||
var collectionName: String
|
||||
var storageLocation: String
|
||||
var rarity: String?
|
||||
var colorIdentity: [String]?
|
||||
|
||||
// Grading Fields
|
||||
var gradingService: String? // PSA, BGS
|
||||
var grade: String? // 10, 9.5
|
||||
var certNumber: String? // 123456
|
||||
var isCustomValuation: Bool = false
|
||||
var isSerialized: Bool? = false
|
||||
var currencyCode: String?
|
||||
|
||||
init(from scan: CardMetadata, imageName: String, collection: String, location: String) {
|
||||
self.id = UUID()
|
||||
self.scryfallID = "\(scan.setCode)-\(scan.collectorNumber)"
|
||||
self.name = scan.name
|
||||
self.setCode = scan.setCode
|
||||
self.collectorNumber = scan.collectorNumber
|
||||
self.imageFileName = imageName
|
||||
self.condition = AppConfig.Defaults.defaultCondition
|
||||
self.foilType = AppConfig.Defaults.defaultFoil
|
||||
self.currentValuation = scan.priceScanned
|
||||
self.previousValuation = scan.priceScanned
|
||||
self.dateAdded = Date()
|
||||
self.classification = "Unknown"
|
||||
self.collectionName = collection
|
||||
self.storageLocation = location
|
||||
self.rarity = scan.rarity
|
||||
self.colorIdentity = scan.colorIdentity
|
||||
self.isSerialized = scan.isSerialized
|
||||
}
|
||||
|
||||
/// Full memberwise init used by SavedCardModel (SwiftData) ↔ SavedCard conversion.
|
||||
init(id: UUID, scryfallID: String, name: String, setCode: String, collectorNumber: String,
|
||||
imageFileName: String, condition: String, foilType: String, currentValuation: Double?,
|
||||
previousValuation: Double?, dateAdded: Date, classification: String, collectionName: String,
|
||||
storageLocation: String, rarity: String?, colorIdentity: [String]?,
|
||||
gradingService: String?, grade: String?, certNumber: String?,
|
||||
isCustomValuation: Bool, isSerialized: Bool?, currencyCode: String?) {
|
||||
self.id = id
|
||||
self.scryfallID = scryfallID
|
||||
self.name = name
|
||||
self.setCode = setCode
|
||||
self.collectorNumber = collectorNumber
|
||||
self.imageFileName = imageFileName
|
||||
self.condition = condition
|
||||
self.foilType = foilType
|
||||
self.currentValuation = currentValuation
|
||||
self.previousValuation = previousValuation
|
||||
self.dateAdded = dateAdded
|
||||
self.classification = classification
|
||||
self.collectionName = collectionName
|
||||
self.storageLocation = storageLocation
|
||||
self.rarity = rarity
|
||||
self.colorIdentity = colorIdentity
|
||||
self.gradingService = gradingService
|
||||
self.grade = grade
|
||||
self.certNumber = certNumber
|
||||
self.isCustomValuation = isCustomValuation
|
||||
self.isSerialized = isSerialized
|
||||
self.currencyCode = currencyCode
|
||||
}
|
||||
}
|
||||
|
||||
enum MatchResult {
|
||||
case exact(CardMetadata)
|
||||
case ambiguous(name: String, candidates: [CardMetadata])
|
||||
case unknown
|
||||
}
|
||||
156
IYmtg_App_iOS/Data/Models/SavedCardModel.swift
Normal file
156
IYmtg_App_iOS/Data/Models/SavedCardModel.swift
Normal file
@@ -0,0 +1,156 @@
|
||||
import SwiftData
|
||||
import Foundation
|
||||
|
||||
// MARK: - SAVED CARD MODEL
|
||||
// SwiftData @Model class for structured persistence with automatic CloudKit sync.
|
||||
// Mirrors the SavedCard value-type struct so the rest of the app stays unchanged.
|
||||
// Requires iOS 17+. Set minimum deployment target to iOS 17 in Xcode.
|
||||
|
||||
@Model
|
||||
final class SavedCardModel {
|
||||
@Attribute(.unique) var id: UUID
|
||||
var scryfallID: String
|
||||
var name: String
|
||||
var setCode: String
|
||||
var collectorNumber: String
|
||||
var imageFileName: String
|
||||
var condition: String
|
||||
var foilType: String
|
||||
var currentValuation: Double?
|
||||
var previousValuation: Double?
|
||||
var dateAdded: Date
|
||||
var classification: String
|
||||
var collectionName: String
|
||||
var storageLocation: String
|
||||
var rarity: String?
|
||||
var colorIdentity: [String]?
|
||||
var gradingService: String?
|
||||
var grade: String?
|
||||
var certNumber: String?
|
||||
var isCustomValuation: Bool
|
||||
var isSerialized: Bool?
|
||||
var currencyCode: String?
|
||||
|
||||
init(
|
||||
id: UUID = UUID(),
|
||||
scryfallID: String,
|
||||
name: String,
|
||||
setCode: String,
|
||||
collectorNumber: String,
|
||||
imageFileName: String,
|
||||
condition: String,
|
||||
foilType: String,
|
||||
currentValuation: Double? = nil,
|
||||
previousValuation: Double? = nil,
|
||||
dateAdded: Date = Date(),
|
||||
classification: String = "Unknown",
|
||||
collectionName: String,
|
||||
storageLocation: String,
|
||||
rarity: String? = nil,
|
||||
colorIdentity: [String]? = nil,
|
||||
gradingService: String? = nil,
|
||||
grade: String? = nil,
|
||||
certNumber: String? = nil,
|
||||
isCustomValuation: Bool = false,
|
||||
isSerialized: Bool? = false,
|
||||
currencyCode: String? = nil
|
||||
) {
|
||||
self.id = id
|
||||
self.scryfallID = scryfallID
|
||||
self.name = name
|
||||
self.setCode = setCode
|
||||
self.collectorNumber = collectorNumber
|
||||
self.imageFileName = imageFileName
|
||||
self.condition = condition
|
||||
self.foilType = foilType
|
||||
self.currentValuation = currentValuation
|
||||
self.previousValuation = previousValuation
|
||||
self.dateAdded = dateAdded
|
||||
self.classification = classification
|
||||
self.collectionName = collectionName
|
||||
self.storageLocation = storageLocation
|
||||
self.rarity = rarity
|
||||
self.colorIdentity = colorIdentity
|
||||
self.gradingService = gradingService
|
||||
self.grade = grade
|
||||
self.certNumber = certNumber
|
||||
self.isCustomValuation = isCustomValuation
|
||||
self.isSerialized = isSerialized
|
||||
self.currencyCode = currencyCode
|
||||
}
|
||||
|
||||
convenience init(from card: SavedCard) {
|
||||
self.init(
|
||||
id: card.id,
|
||||
scryfallID: card.scryfallID,
|
||||
name: card.name,
|
||||
setCode: card.setCode,
|
||||
collectorNumber: card.collectorNumber,
|
||||
imageFileName: card.imageFileName,
|
||||
condition: card.condition,
|
||||
foilType: card.foilType,
|
||||
currentValuation: card.currentValuation,
|
||||
previousValuation: card.previousValuation,
|
||||
dateAdded: card.dateAdded,
|
||||
classification: card.classification,
|
||||
collectionName: card.collectionName,
|
||||
storageLocation: card.storageLocation,
|
||||
rarity: card.rarity,
|
||||
colorIdentity: card.colorIdentity,
|
||||
gradingService: card.gradingService,
|
||||
grade: card.grade,
|
||||
certNumber: card.certNumber,
|
||||
isCustomValuation: card.isCustomValuation,
|
||||
isSerialized: card.isSerialized,
|
||||
currencyCode: card.currencyCode
|
||||
)
|
||||
}
|
||||
|
||||
func update(from card: SavedCard) {
|
||||
name = card.name
|
||||
setCode = card.setCode
|
||||
collectorNumber = card.collectorNumber
|
||||
condition = card.condition
|
||||
foilType = card.foilType
|
||||
currentValuation = card.currentValuation
|
||||
previousValuation = card.previousValuation
|
||||
classification = card.classification
|
||||
collectionName = card.collectionName
|
||||
storageLocation = card.storageLocation
|
||||
rarity = card.rarity
|
||||
colorIdentity = card.colorIdentity
|
||||
gradingService = card.gradingService
|
||||
grade = card.grade
|
||||
certNumber = card.certNumber
|
||||
isCustomValuation = card.isCustomValuation
|
||||
isSerialized = card.isSerialized
|
||||
currencyCode = card.currencyCode
|
||||
}
|
||||
|
||||
func toSavedCard() -> SavedCard {
|
||||
SavedCard(
|
||||
id: id,
|
||||
scryfallID: scryfallID,
|
||||
name: name,
|
||||
setCode: setCode,
|
||||
collectorNumber: collectorNumber,
|
||||
imageFileName: imageFileName,
|
||||
condition: condition,
|
||||
foilType: foilType,
|
||||
currentValuation: currentValuation,
|
||||
previousValuation: previousValuation,
|
||||
dateAdded: dateAdded,
|
||||
classification: classification,
|
||||
collectionName: collectionName,
|
||||
storageLocation: storageLocation,
|
||||
rarity: rarity,
|
||||
colorIdentity: colorIdentity,
|
||||
gradingService: gradingService,
|
||||
grade: grade,
|
||||
certNumber: certNumber,
|
||||
isCustomValuation: isCustomValuation,
|
||||
isSerialized: isSerialized,
|
||||
currencyCode: currencyCode
|
||||
)
|
||||
}
|
||||
}
|
||||
15
IYmtg_App_iOS/Data/Network/NetworkMonitor.swift
Normal file
15
IYmtg_App_iOS/Data/Network/NetworkMonitor.swift
Normal file
@@ -0,0 +1,15 @@
|
||||
import Network
|
||||
import Combine
|
||||
import Foundation
|
||||
|
||||
// MARK: - NETWORK MONITOR
|
||||
class NetworkMonitor: ObservableObject {
|
||||
static let shared = NetworkMonitor()
|
||||
private let monitor = NWPathMonitor()
|
||||
@Published var isConnected = true
|
||||
|
||||
init() {
|
||||
monitor.pathUpdateHandler = { path in DispatchQueue.main.async { self.isConnected = path.status == .satisfied } }
|
||||
monitor.start(queue: DispatchQueue.global(qos: .background))
|
||||
}
|
||||
}
|
||||
121
IYmtg_App_iOS/Data/Network/ScryfallAPI.swift
Normal file
121
IYmtg_App_iOS/Data/Network/ScryfallAPI.swift
Normal file
@@ -0,0 +1,121 @@
|
||||
import Foundation
|
||||
|
||||
// MARK: - SCRYFALL THROTTLER
|
||||
actor ScryfallThrottler {
|
||||
static let shared = ScryfallThrottler()
|
||||
private var nextAllowedTime = Date.distantPast
|
||||
|
||||
func wait() async {
|
||||
let now = Date()
|
||||
let targetTime = max(now, nextAllowedTime)
|
||||
nextAllowedTime = targetTime.addingTimeInterval(0.1)
|
||||
|
||||
let waitTime = targetTime.timeIntervalSince(now)
|
||||
if waitTime > 0 {
|
||||
try? await Task.sleep(nanoseconds: UInt64(waitTime * 1_000_000_000))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SCRYFALL API (formerly InsuranceEngine)
|
||||
class ScryfallAPI {
|
||||
struct PricingIdentifier: Codable { let set: String; let collector_number: String }
|
||||
struct ScryfallData {
|
||||
let price: Double?
|
||||
let typeLine: String
|
||||
let rarity: String?
|
||||
let colors: [String]?
|
||||
let isSerialized: Bool
|
||||
}
|
||||
|
||||
static func getPriceKey(foilType: String, currency: CurrencyCode) -> String {
|
||||
if foilType.caseInsensitiveCompare("Etched") == .orderedSame { return "\(currency.scryfallKey)_etched" }
|
||||
let isFoil = foilType != "None" && foilType != AppConfig.Defaults.defaultFoil
|
||||
let base = currency.scryfallKey
|
||||
return isFoil ? "\(base)_foil" : base
|
||||
}
|
||||
|
||||
static func updateTrends(cards: [SavedCard], currency: CurrencyCode, force: Bool = false, updateTimestamp: Bool = true) async -> ([UUID: Double], [UUID: (String?, [String]?, Bool)]) {
|
||||
if !NetworkMonitor.shared.isConnected { return ([:], [:]) }
|
||||
let lastUpdate = UserDefaults.standard.object(forKey: "LastPriceUpdate") as? Date ?? Date.distantPast
|
||||
let isCacheExpired = Date().timeIntervalSince(lastUpdate) >= 86400
|
||||
|
||||
// Optimization: If cache is fresh, only fetch cards that are missing a price (Smart Partial Refresh)
|
||||
let cardsToFetch = (force || isCacheExpired) ? cards : cards.filter { $0.currentValuation == nil }
|
||||
if cardsToFetch.isEmpty { return ([:], [:]) }
|
||||
|
||||
var updates: [UUID: Double] = [:]
|
||||
var metadataUpdates: [UUID: (String?, [String]?, Bool)] = [:]
|
||||
let marketCards = cardsToFetch.filter { !$0.isCustomValuation }
|
||||
let chunks = stride(from: 0, to: marketCards.count, by: 75).map { Array(marketCards[$0..<min($0 + 75, marketCards.count)]) }
|
||||
|
||||
for chunk in chunks {
|
||||
await ScryfallThrottler.shared.wait()
|
||||
let identifiers = chunk.map { PricingIdentifier(set: $0.setCode, collector_number: $0.collectorNumber) }
|
||||
guard let body = try? JSONEncoder().encode(["identifiers": identifiers]) else { continue }
|
||||
|
||||
var request = URLRequest(url: URL(string: "https://api.scryfall.com/cards/collection")!)
|
||||
request.httpMethod = "POST"
|
||||
request.httpBody = body
|
||||
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||
request.addValue(AppConfig.scryfallUserAgent, forHTTPHeaderField: "User-Agent")
|
||||
request.addValue("application/json", forHTTPHeaderField: "Accept")
|
||||
|
||||
if let (data, response) = try? await URLSession.shared.data(for: request),
|
||||
(response as? HTTPURLResponse)?.statusCode == 200,
|
||||
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
|
||||
let dataArray = json["data"] as? [[String: Any]] {
|
||||
|
||||
for cardData in dataArray {
|
||||
if let set = cardData["set"] as? String, let num = cardData["collector_number"] as? String,
|
||||
let prices = cardData["prices"] as? [String: Any] {
|
||||
|
||||
let matchingCards = chunk.filter { $0.setCode.caseInsensitiveCompare(set) == .orderedSame && $0.collectorNumber == num }
|
||||
for card in matchingCards {
|
||||
let priceKey = getPriceKey(foilType: card.foilType, currency: currency)
|
||||
|
||||
// Capture Metadata (Backfill)
|
||||
let rarity = cardData["rarity"] as? String
|
||||
let colors = cardData["color_identity"] as? [String]
|
||||
let promoTypes = cardData["promo_types"] as? [String]
|
||||
let isSer = promoTypes?.contains("serialized") ?? false
|
||||
metadataUpdates[card.id] = (rarity, colors, isSer)
|
||||
|
||||
if let newPriceStr = prices[priceKey] as? String,
|
||||
let newPrice = Double(newPriceStr),
|
||||
!newPrice.isNaN, !newPrice.isInfinite {
|
||||
updates[card.id] = newPrice
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (force || isCacheExpired) && updateTimestamp { UserDefaults.standard.set(Date(), forKey: "LastPriceUpdate") }
|
||||
return (updates, metadataUpdates)
|
||||
}
|
||||
|
||||
static func fetchPrice(setCode: String, number: String, foilType: String, currency: CurrencyCode) async -> ScryfallData {
|
||||
if !NetworkMonitor.shared.isConnected { return ScryfallData(price: nil, typeLine: "Offline", rarity: nil, colors: nil, isSerialized: false) }
|
||||
await ScryfallThrottler.shared.wait()
|
||||
|
||||
let encodedSet = setCode.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? setCode
|
||||
let encodedNum = number.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? number
|
||||
|
||||
guard let url = URL(string: "https://api.scryfall.com/cards/\(encodedSet)/\(encodedNum)") else { return ScryfallData(price: nil, typeLine: "Error", rarity: nil, colors: nil, isSerialized: false) }
|
||||
var request = URLRequest(url: url)
|
||||
request.addValue(AppConfig.scryfallUserAgent, forHTTPHeaderField: "User-Agent")
|
||||
|
||||
guard let (data, _) = try? await URLSession.shared.data(for: request),
|
||||
let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return ScryfallData(price: nil, typeLine: "Unknown", rarity: nil, colors: nil, isSerialized: false) }
|
||||
|
||||
let prices = json["prices"] as? [String: Any]
|
||||
let priceKey = getPriceKey(foilType: foilType, currency: currency)
|
||||
let price = Double(prices?[priceKey] as? String ?? "")
|
||||
let rarity = json["rarity"] as? String
|
||||
let colors = json["color_identity"] as? [String]
|
||||
let promoTypes = json["promo_types"] as? [String]
|
||||
let isSer = promoTypes?.contains("serialized") ?? false
|
||||
return ScryfallData(price: price, typeLine: (json["type_line"] as? String) ?? "", rarity: rarity, colors: colors, isSerialized: isSer)
|
||||
}
|
||||
}
|
||||
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