Skip to content

Instantly share code, notes, and snippets.

@niczyja
Last active May 4, 2021 12:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niczyja/a92776bd03134f8330af60f07f4b85e2 to your computer and use it in GitHub Desktop.
Save niczyja/a92776bd03134f8330af60f07f4b85e2 to your computer and use it in GitHub Desktop.
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "app container name")
guard let fileContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "your group.app.identifier") else {
fatalError("Shared file container could not be created.")
}
let groupStoreUrl = fileContainer.appendingPathComponent("app container name.sqlite")
let hasOldStore = FileManager.default.fileExists(atPath: container.persistentStoreDescriptions.first?.url?.path ?? "")
let needsMigration = hasOldStore && container.persistentStoreDescriptions.first?.url?.absoluteString != groupStoreUrl.absoluteString
if !hasOldStore {
let description = NSPersistentStoreDescription(url: groupStoreUrl)
container.persistentStoreDescriptions = [description]
}
container.loadPersistentStores { (storeDescription, error) in
guard error == nil else {
print("Error loading persistent store", error!.localizedDescription)
return
}
guard needsMigration else {
print("Store migration not needed")
return
}
guard let oldStoreUrl = storeDescription.url,
let oldStore = container.persistentStoreCoordinator.persistentStore(for: oldStoreUrl) else {
print("Cannot locate old store")
return
}
do {
try container.persistentStoreCoordinator.migratePersistentStore(oldStore, to: groupStoreUrl, options: nil, withType: NSSQLiteStoreType)
var error: NSError?
NSFileCoordinator().coordinate(writingItemAt: oldStoreUrl, options: .forDeleting, error: &error) { (urlForModifying) in
do {
try FileManager.default.removeItem(at: urlForModifying)
} catch let error {
print("Error deleting old store file", error.localizedDescription)
}
}
if error != nil {
print("Error coordinating deleting old store", error!.localizedDescription)
}
} catch let error {
print("Error migrating store", error.localizedDescription)
}
}
return container
}()
@niczyja
Copy link
Author

niczyja commented May 4, 2021

Migrate core data persistent store from app container to security application group identifier for use with app extensions and so on.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment