I have a basic SwiftUI app that inits a NSPersistentCloudKitContainer based persistent stack at app start and injects the viewContext into the Environment and passes it to all the views of my app. That works as expected. The PersistentContainer is configured to sync with CloudKit by default.
Now I want to provide the user a way to toggle iCloud sync in the app settings, I do this by setting cloudKitContainerOptions to nil in the StoreDescription and re-initializing the persistent stack.
The problem is that now the ManagedObjectContext in the Environment is outdated and would need to be re-injected as well. Does anyone have any idea how to do this? I have my UserSettings ObservableObject in the App struct but I am not sure how I can trigger a re-inject of the View:
@main
struct MyApp: App {
[...]
@ObservedObject private var userSettings: UserSettings
private let persistenceController: PersistenceController
var body: some Scene {
WindowGroup {
let service1 = Service1(context: persistenceController.container.viewContext)
let service2 = Service2(context: persistenceController.container.viewContext)
HomeTabView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
.environmentObject(service1)
.environmentObject(service2)
}
}
}
Or is it possible to toggle iCloud sync without re-initializing the whole NSPersistentCloudKitContainer?