diff --git a/Shared/LocalStorageManager.swift b/Shared/LocalStorageManager.swift index 739ae8d..b938fdf 100644 --- a/Shared/LocalStorageManager.swift +++ b/Shared/LocalStorageManager.swift @@ -10,6 +10,17 @@ final class LocalStorageManager { public static var standard = LocalStorageManager() public let container: NSPersistentContainer + private var oldStoreURL: URL { + let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first! + return appSupport.appendingPathComponent("LocalStorageModel.sqlite") + } + + private var sharedStoreURL: URL { + let id = "group.com.abunchtell.writefreely" + let groupContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: id)! + return groupContainer.appendingPathComponent("LocalStorageModel.sqlite") + } + init() { // Set up the persistent container. container = NSPersistentContainer(name: "LocalStorageModel") @@ -56,6 +67,29 @@ final class LocalStorageManager { print("Error: Failed to purge cached collections.") } } + + func migrateStore(for container: NSPersistentContainer) { + let coordinator = container.persistentStoreCoordinator + + guard let oldStore = coordinator.persistentStore(for: oldStoreURL) else { + return + } + + do { + try coordinator.migratePersistentStore(oldStore, + to: sharedStoreURL, + options: nil, + withType: NSSQLiteStoreType) + } catch { + fatalError("Something went wrong migrating the store: \(error)") + } + + do { + try FileManager.default.removeItem(at: oldStoreURL) + } catch { + fatalError("Something went wrong while deleting the old store: \(error)") + } + } } private extension LocalStorageManager {