wip
This commit is contained in:
33
Workouts/Schema/CloudKitSyncObserver.swift
Normal file
33
Workouts/Schema/CloudKitSyncObserver.swift
Normal file
@ -0,0 +1,33 @@
|
||||
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())
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user