swiftxcodeswiftuiswiftdataappgroups

How can I migrate existing SwiftData to App Group


I have an existing app which uses SwiftData, and there is now a requirement to add extensions which would need to access this data.

I have tried using an App Group, which will share the data, but it would mean that data on existing installations would no longer be available.

Is there any way of doing this while preserving - or somehow at least migrating - the existing data so that it is still available?


Solution

  • I encountered the same issue, and here’s how I resolved it: First of all, find the old store:

    guard let legacyStoreURL = FileManager.default
        .urls(for: .applicationSupportDirectory, in: .userDomainMask)
        .first?
        .appendingPathComponent(databaseFileName) else {
        return
    }
    

    The database name is usually default.store

    Next, create a model container with the old store's location configuration:

    let legacyConfig = ModelConfiguration(url: legacyStoreURL)
    let legacyContainer = try ModelContainer(for: dataSchema, configurations: [legacyConfig])
    

    After that, it should be pretty straightforward. You can use any logic to get data from your new (appGroup) store, if you have one. Then, simply insert the data from the old store into the new one.

    Finally, if you no longer need the old store, you can delete it: FileManager.default.removeItem(at: legacyStoreURL)