Sesame-iOS/Sesame/Common/Extensions/App+Extensions.swift

38 lines
1.2 KiB
Swift
Raw Permalink Normal View History

2023-12-27 21:57:17 +01:00
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")
}
}
}