Search code examples
swiftswiftdata

Error setting up iCloud Documents with SwiftData


I'm trying to use an iCloud Documents folder inside my App that uses SwiftData. I've set up the entitlements, but the App crashes on startup.

The error happens here:

var sharedModelContainer: ModelContainer = {
    let schema = Schema([SomeModel.self])
    let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)

    do {
        return try ModelContainer(for: schema, configurations: [modelConfiguration])
    } catch {
        fatalError("Could not create ModelContainer: \(error)") // <- crash here
    }
}()

This is the error message: Thread 1: Fatal error: Could not create ModelContainer: SwiftDataError(_error: SwiftData.SwiftDataError._Error.loadIssueModelContainer)

I'm only using the iCloud Documents service, not CloudKit. The error is gone as soon as I uncheck iCloud Documents under Capabilities.


Solution

  • Even though I wasn’t using CloudKit, following the CloudKit requirements for swiftData seems to have fixed the issue:

    • No @Attribute(.unique) on any property
    • All properties must either have default values or be marked as optional, alongside their initializer.
    • All relationships must be marked optional.

    They show up as errors when ticking CloudKit. Otherwise it just crashed without any info.