Last active
May 4, 2021 12:25
-
-
Save niczyja/a92776bd03134f8330af60f07f4b85e2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
}() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Migrate core data persistent store from app container to security application group identifier for use with app extensions and so on.