Sesame-iOS/Sesame/Common/Extensions/App+Extensions.swift
2023-12-27 21:57:17 +01:00

38 lines
1.2 KiB
Swift
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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")
}
}
}