Created
January 16, 2021 07:45
-
-
Save SlappyAUS/c43113604e07efd03bfa5e2613e73c85 to your computer and use it in GitHub Desktop.
Seeding core Data #swift #coredata
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
func getDocumentsDirectory()-> URL { | |
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) | |
let documentsDirectory = paths[0] | |
return documentsDirectory | |
} | |
// MARK: - Core Data stack | |
lazy var persistentContainer: NSPersistentContainer = { | |
let container = NSPersistentContainer(name: "ESLdata") | |
let appName: String = "ESLdata" | |
var persistentStoreDescriptions: NSPersistentStoreDescription | |
let storeUrl = self.getDocumentsDirectory().appendingPathComponent("ESLData.sqlite") | |
if !FileManager.default.fileExists(atPath: (storeUrl.path)) { | |
let seededDataUrl = Bundle.main.url(forResource: appName, withExtension: "sqlite") | |
try! FileManager.default.copyItem(at: seededDataUrl!, to: storeUrl) | |
} | |
let description = NSPersistentStoreDescription() | |
description.shouldInferMappingModelAutomatically = true | |
description.shouldMigrateStoreAutomatically = true | |
description.url = storeUrl | |
container.persistentStoreDescriptions = [description] | |
container.loadPersistentStores(completionHandler: { (storeDescription, error) in | |
if let error = error as NSError? { | |
fatalError("Unresolved error \(error), \(error.userInfo)") | |
} | |
}) | |
return container | |
}() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment