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()) // 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()) } }