SwiftData + CloudKit -- data not loaded on fresh install

Okay, so I created a new Xcode project using SwiftData, and ticked the box for iCloud integration. I added a container on the web dashboard. Then I added “ = Date()” to the definition of Item.timestamp so that it has a default value. I added the container to my Xcode project..

Then I added this “let config” and “let container” and changed the “.modelContainer” like this:

This will successfully add stuff to core data, which also appears in iCloud dashboard.

BUT, if I delete the app and re-launch, I don’t see the existing iCloud data until the SECOND launch, even though the Xcode runtime log shows it fetched it.

Do I need to do some magic to get it to refresh? Is the CloudKit subscription managed by SwiftData or do I need to do something for that?

thanks!

Post not yet marked as solved Up vote post of drewster Down vote post of drewster
3.5k views
  • Per suggestion in Slack's "data-frameworks" WWDC 2023 channel, I submitted Feedback, as FB12245665.

  • @drewster Have you tried using SwiftData locally, i.e., no CloudKit container? When I do that, I lose all data between launches as the underlying -wal gets replaced when the ModelContainer is created.

  • I don’t recall the exact differences offhand, but if you create a new project using SwiftData and without CloudKit, the setup is slightly different. I didn’t have any trouble with data persistence between runs.

Add a Comment

Replies

Without the "= Date()" I get an error. Why is that?

  • When using CloudKit, all fields in your model either need to have a default value or be optional.

Add a Comment

I was wondering if anybody has a solution? I just got my local data to sync with iCloud, that was fun and easy. At first time startup I have to start and stop then restart it so see the data stored in iCloud, or add a record.

My data model is very simple

@Model
final class Person{
    var name: String = ""
    var age: Int = 0
    
    init( name: String, age: Int) {
        self.name = name
        self.age = age
    }
}

Have the APIs changed in iOS 17 beta 7? ModelConfigurations now want a CKDatabase and not an identifier, but the docs have not been updated to show how to create one.

I'm having this exact same issue. Did anyone here happen to work out a solution? My app will work perfectly after adding data but on a fresh install on another device the data is returned as empty. I tried listening for "NSPersistentStoreRemoteChange" events which do come in eventually and then re-fetching the data but not working yet. My gut tells me there has to be a better way. I looked into CKSyncEngine but I really thought it shouldn't be necessary with SwiftData persistence and the fact that my app works fine on the new device on the second launch.