swiftswiftdata

How to completely reset SwiftData programatically?


I'm currently developping an app, which runs on several devices via TestFlight. Since I am still in an early stage my @Models are subject to change quite frequently.

I know that the preferred way of handling changes to the Schema are SchemaMigrationPlans. However due to the limited number of devices I don't want and need to create those. Instead I'd rather just erase the whole SwiftData storage, since I mostly use the storage for caching and widgets.

The problem is, that I cannot even initialize the ModelContainer to delete it afterwards

return try ModelContainer(for: ClassA.self, ClassB.self) // will throw an error

That means, that the only way to get the app running is to reinstall it. My desired behavior is

do {
    let container = try ModelContainer(for: ClassA.self, ClassB.self)
    return container
} catch {
    resetSwiftData()
    let container = try ModelContainer(for: ClassA.self, ClassB.self)
    return container
}

How can I implement resetSwiftData(), if I cannot even create the ModelContainer to locate it?


Solution

  • If you are just using a simple on-disk container, then deleting the file at the container's URL would work. You can get the URL from the ModelConfiguration you used to create the model container.

    do {
        let container = try ModelContainer(for: ClassA.self, ClassB.self)
        return container
    } catch {
        try FileManager.default.removeItem(at: ModelConfiguration(for: ClassA.self, ClassB.self).url)
        let container = try ModelContainer(for: ClassA.self, ClassB.self)
        return container
    }