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>
138 lines
5.8 KiB
Swift
138 lines
5.8 KiB
Swift
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)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|