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

34 lines
1.3 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
// When we receive a notification that CloudKit data changed:
// 1. Create a new UUID to force view refresh
refreshID = UUID()
// 2. Optionally, you can also manually refresh the model context
// This is sometimes needed for complex relationships
Task { @MainActor in
try? modelContext.fetch(FetchDescriptor<Exercise>())
// Add other model types as needed
}
}
}
}
// 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())
}
}