// // WorkoutsApp.swift // Workouts // // Created by rzen on 7/11/25 at 5:04 PM. // // Copyright 2025 Rouslan Zenetl. All Rights Reserved. // import SwiftUI import SwiftData import CloudKit import CoreData @main struct WorkoutsApp: App { let container: ModelContainer @State private var cloudKitObserver: NSObjectProtocol? init() { self.container = WorkoutsContainer.create() // Set up CloudKit notification observation setupCloudKitObservation() } private func setupCloudKitObservation() { // Access the underlying NSPersistentCloudKitContainer if let persistentContainer = Mirror(reflecting: container).descendant("persistentContainer") as? NSPersistentContainer { // Register for remote change notifications cloudKitObserver = NotificationCenter.default.addObserver( forName: NSPersistentCloudKitContainer.eventChangedNotification, object: persistentContainer, queue: .main ) { notification in // Handle the notification self.handleCloudKitNotification(notification) } } } private func handleCloudKitNotification(_ notification: Notification) { guard let event = notification.userInfo?[NSPersistentCloudKitContainer.eventNotificationUserInfoKey] as? NSPersistentCloudKitContainer.Event else { return } // Log the event for debugging print("CloudKit event: \(event.type), \(event.succeeded ? "succeeded" : "failed")") // If the event was a successful import, refresh the UI if event.type == .import, event.succeeded { // Create a new context to force UI refresh let context = ModelContext(container) // Trigger UI refresh by posting a notification that views can observe NotificationCenter.default.post(name: .cloudKitDataDidChange, object: nil) } } var body: some Scene { WindowGroup { ContentView() } .modelContainer(container) } } // Extension to define the notification name extension Notification.Name { static let cloudKitDataDidChange = Notification.Name("cloudKitDataDidChange") }