Hi,
I am implementing a premium feature in my app where CloudKit syncing is available only for "Pro" users.
The Workflow:
- Free Users: I initialize the
ModelContainerwithcloudKitDatabase: .noneso their data stays local. - Pro Upgrade: When a user purchases a subscription, I restart the container with
cloudKitDatabase: .automaticto enable syncing.
The Problem: If a user starts as "Free" (creates local data) and later upgrades to "Pro", the app crashes immediately upon launch with the following error:
Fatal error: Failed to create ModelContainer: SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer, _explanation: nil)
It seems that SwiftData fails to load the existing data once the configuration changes to expect a CloudKit-backed store.
My Question: Is there a supported way to "toggle" CloudKit on for an existing local dataset without causing this crash? I want the user's existing local data to start syncing once they pay, but currently, it just crashes.
My code:
import Foundation
import SwiftData
public enum DataModelEnum: String {
case task, calendar
public static let container: ModelContainer = {
let isSyncEnabled = UserDefaults.isProUser
let config = ModelConfiguration(
groupContainer: .identifier("group.com.yourcompany.myApp"),
cloudKitDatabase: isSyncEnabled ? .automatic : .none
)
do {
return try ModelContainer(for: TaskModel.self, CalendarModel.self, configurations: config)
} catch {
fatalError("Failed to create ModelContainer: \(error)")
}
}()
}