Skip to content

Instantly share code, notes, and snippets.

@samwarnick
Last active January 25, 2023 16:11
Show Gist options
  • Save samwarnick/ea5a4a567ee0a86b8c07b3c9d3d47b2f to your computer and use it in GitHub Desktop.
Save samwarnick/ea5a4a567ee0a86b8c07b3c9d3d47b2f to your computer and use it in GitHub Desktop.
Migrate to app group
// In my core data stack
let container = NSPersistentCloudKitContainer(name: "DataModel")
let storeUrl = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: groupIdentifier)!.appendingPathComponent("DataModel.sqlite")
// Enable history tracking and remote notifications
guard let description = container.persistentStoreDescriptions.first else {
fatalError("###\(#function): Failed to retrieve a persistent store description.")
}
description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
let defaultUrl = description.url
description.url = storeUrl
if let oldStoreUrl = defaultUrl, FileManager.default.fileExists(atPath: oldStoreUrl.path) {
self.migrateStoreToAppGroup(oldStoreUrl: oldStoreUrl, storeUrl: storeUrl)
}
// and...
private func migrateStoreToAppGroup(oldStoreUrl: URL, storeUrl: URL) {
let url = Bundle.main.url(forResource: "DataModel", withExtension: "momd")!
let managedObjectModel = NSManagedObjectModel(contentsOf: url)!
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
do {
try coordinator.replacePersistentStore(at: storeUrl, destinationOptions: [
NSPersistentHistoryTrackingKey: true,
NSPersistentStoreRemoteChangeNotificationPostOptionKey: true
], withPersistentStoreFrom: oldStoreUrl, sourceOptions: [
NSPersistentHistoryTrackingKey: true,
NSPersistentStoreRemoteChangeNotificationPostOptionKey: true
], ofType: NSSQLiteStoreType)
try FileManager.default.removeItem(at: oldStoreUrl)
} catch {
Logging.logError(error)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment