87 lines
2.8 KiB
Swift
87 lines
2.8 KiB
Swift
//
|
||
// 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
|
||
import UIKit
|
||
|
||
@main
|
||
struct WorkoutsApp: App {
|
||
// Control whether to prevent device auto-lock
|
||
@State private var preventAutoLock: Bool = true
|
||
let container: ModelContainer
|
||
@State private var cloudKitObserver: NSObjectProtocol?
|
||
|
||
init() {
|
||
self.container = AppContainer.create()
|
||
|
||
// Set up CloudKit notification observation
|
||
setupCloudKitObservation()
|
||
|
||
// Disable screen auto-lock
|
||
UIApplication.shared.isIdleTimerDisabled = true
|
||
}
|
||
|
||
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()
|
||
.onAppear {
|
||
// Ensure auto-lock is disabled when app appears
|
||
UIApplication.shared.isIdleTimerDisabled = preventAutoLock
|
||
}
|
||
.onDisappear {
|
||
// Re-enable auto-lock when app disappears
|
||
UIApplication.shared.isIdleTimerDisabled = false
|
||
}
|
||
}
|
||
.modelContainer(container)
|
||
}
|
||
}
|
||
|
||
// Extension to define the notification name
|
||
extension Notification.Name {
|
||
static let cloudKitDataDidChange = Notification.Name("cloudKitDataDidChange")
|
||
}
|