48 lines
2.0 KiB
Swift
48 lines
2.0 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 {
|
|
// for entity in modelContext.container.schema.entities {
|
|
// fetchAll<entity.Type>(of: entity.Type, from: modelContext)
|
|
// }
|
|
// } catch {
|
|
// print("ERROR: failed to fetch data on CloudKit change")
|
|
// }
|
|
//
|
|
// try? modelContext.fetch(FetchDescriptor<Exercise>())
|
|
// try? modelContext.fetch(FetchDescriptor<ExerciseType>())
|
|
// try? modelContext.fetch(FetchDescriptor<Muscle>())
|
|
// try? modelContext.fetch(FetchDescriptor<MuscleGroup>())
|
|
// try? modelContext.fetch(FetchDescriptor<Exercise>())
|
|
// try? modelContext.fetch(FetchDescriptor<Exercise>())
|
|
// try? modelContext.fetch(FetchDescriptor<Exercise>())
|
|
// try? modelContext.fetch(FetchDescriptor<Exercise>())
|
|
// TODO: add more entities?
|
|
}
|
|
}
|
|
}
|
|
|
|
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())
|
|
}
|
|
}
|