Files
workouts/Workouts/Schema/CloudKitSyncObserver.swift
2025-07-25 17:42:25 -04:00

39 lines
1.5 KiB
Swift

import SwiftUI
import SwiftData
/// A view modifier that refreshes the view when CloudKit data changes
struct CloudKitSyncObserver: ViewModifier {
@Environment(\.modelContext) private var modelContext
@State private var refreshID = UUID()
func body(content: Content) -> some View {
content
.id(refreshID) // Force view refresh when this changes
.onReceive(NotificationCenter.default.publisher(for: .cloudKitDataDidChange)) { _ in
refreshID = UUID()
Task { @MainActor in
do {
let _ = try await fetchAll(of: Exercise.self, from: modelContext)
let _ = try await fetchAll(of: Split.self, from: modelContext)
let _ = try await fetchAll(of: Workout.self, from: modelContext)
let _ = try await fetchAll(of: WorkoutLog.self, from: modelContext)
} catch {
print("ERROR: failed to fetch \(error.localizedDescription)")
}
}
}
}
private func fetchAll<T: PersistentModel>(of type: T.Type,from modelContext: ModelContext) async throws -> [T]? {
try modelContext.fetch(FetchDescriptor<T>())
}
}
// Extension to make it easier to use the modifier
extension View {
/// Adds observation for CloudKit sync changes and refreshes the view when changes occur
func observeCloudKitChanges() -> some View {
self.modifier(CloudKitSyncObserver())
}
}