wip
This commit is contained in:
@ -10,17 +10,51 @@
|
||||
|
||||
import SwiftUI
|
||||
import SwiftData
|
||||
import CloudKit
|
||||
import CoreData
|
||||
|
||||
@main
|
||||
struct WorkoutsApp: App {
|
||||
let container: ModelContainer
|
||||
let container: ModelContainer
|
||||
@State private var cloudKitObserver: NSObjectProtocol?
|
||||
|
||||
init() {
|
||||
var shouldCreateDefaults = false
|
||||
self.container = WorkoutsContainer.create(shouldCreateDefaults: &shouldCreateDefaults)
|
||||
self.container = WorkoutsContainer.create()
|
||||
|
||||
if shouldCreateDefaults {
|
||||
InitialData.create(modelContext: ModelContext(container))
|
||||
// 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)
|
||||
}
|
||||
}
|
||||
|
||||
@ -31,3 +65,8 @@ struct WorkoutsApp: App {
|
||||
.modelContainer(container)
|
||||
}
|
||||
}
|
||||
|
||||
// Extension to define the notification name
|
||||
extension Notification.Name {
|
||||
static let cloudKitDataDidChange = Notification.Name("cloudKitDataDidChange")
|
||||
}
|
||||
|
Reference in New Issue
Block a user