From f55ae3c621305eb47f69d591ceb2c99568a24554 Mon Sep 17 00:00:00 2001 From: Angelo Stavrow Date: Fri, 8 Oct 2021 17:16:01 -0400 Subject: [PATCH] Implement initial store-migration functionality --- Shared/LocalStorageManager.swift | 34 ++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) 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 {