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

73 lines
2.3 KiB
Swift
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// WorkoutsApp.swift
// Workouts
//
// Created by rzen on 7/11/25 at 5:04PM.
//
// 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")
}