38 lines
1.2 KiB
Swift
38 lines
1.2 KiB
Swift
import SwiftUI
|
||
import SwiftData
|
||
|
||
extension App {
|
||
|
||
static func loadModelContainer() -> ModelContainer {
|
||
do {
|
||
return try ModelContainer(for: HistoryItem.self)
|
||
} catch {
|
||
print("[WARNING] Removing default SwiftData storage")
|
||
removeDefaultModelContainer()
|
||
}
|
||
// Try again to load an empty container
|
||
do {
|
||
return try ModelContainer(for: HistoryItem.self)
|
||
} catch {
|
||
fatalError("Failed to create empty model container: \(error)")
|
||
}
|
||
}
|
||
|
||
private static func removeDefaultModelContainer() {
|
||
guard let appSupportDir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).last else {
|
||
fatalError("Failed to get application support directory")
|
||
}
|
||
do {
|
||
try FileManager.default.contentsOfDirectory(at: appSupportDir, includingPropertiesForKeys: nil)
|
||
.filter { $0.lastPathComponent.hasPrefix("default") }
|
||
.forEach {
|
||
try FileManager.default.removeItem(at: $0)
|
||
}
|
||
} catch {
|
||
print(error)
|
||
fatalError("Failed to remove default SwiftData database files")
|
||
}
|
||
}
|
||
|
||
}
|