How to load a new Core Data file in the shared container? - core-data

I was working with NSPersistentCloudKitContainer using the Apple sample code, and the setup is very simple like this:
lazy var persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "Name")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
But now I have a need to change to use a database that is in the shared container so that it can be used with extension.
I tried to change it to this code
lazy var persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "Name")
// Create a store description for a CloudKit-backed local store
let storeURL = URL.storeURL(for: "group.com.Name", databaseName: "Name")
let cloudStoreDescription =
NSPersistentStoreDescription(url: storeURL)
cloudStoreDescription.configuration = "Default"
// Set the container options on the cloud store
cloudStoreDescription.cloudKitContainerOptions =
NSPersistentCloudKitContainerOptions(
containerIdentifier: "iCloud.com.Name")
// Update the container's list of store descriptions
container.persistentStoreDescriptions = [cloudStoreDescription]
// Load both stores
container.loadPersistentStores { storeDescription, error in
guard error == nil else {
fatalError("Could not load persistent stores. \(error!)")
}
}
return container
}()
public extension URL {
/// Returns a URL for the given app group and database pointing to the sqlite database.
static func storeURL(for appGroup: String, databaseName: String) -> URL {
guard let fileContainer = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
fatalError("Shared file container could not be created.")
}
return fileContainer.appendingPathComponent("\(databaseName).sqlite")
}
}
but I got this error
Fatal error: Could not load persistent stores. Error Domain=NSCocoaErrorDomain Code=134060 "A Core Data error occurred." UserInfo={NSLocalizedFailureReason=Unable to find a configuration named 'Default' in the specified managed object model.}:

Related

NSPersistentClouKitContainer creates CD_CKRecords but does not export values

I am converting existing app from NSPersistentContainer to NSPersistentCloudKitContainer
AppDelegate code:
lazy var persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name:"GridModel")
// enable history tracking and remote notifications
guard let publicStoreDescription = container.persistentStoreDescriptions.first else {
fatalError("###\(#function): failed to retrieve a persistent store description.")
}
// public
let publicStoreUrl = publicStoreDescription.url!.deletingLastPathComponent().appendingPathComponent("GridModel-public.sqlite")
publicStoreDescription.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
publicStoreDescription.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey)
let containerIdentifier = publicStoreDescription.cloudKitContainerOptions!.containerIdentifier
let publicStoreOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: containerIdentifier)
if #available(iOS 14.0, *) {
publicStoreOptions.databaseScope = CKDatabaseScope.public
} else {
// Fallback on earlier versions???
}
publicStoreDescription.cloudKitContainerOptions = publicStoreOptions
print(containerIdentifier)
container.loadPersistentStores(completionHandler: { (loadedStoreDescription, error) in
if let loadError = error as NSError? {
fatalError("###\(#function): Failed to load persistent stores:\(loadError)")
} else if let cloudKitContainerOptions = loadedStoreDescription.cloudKitContainerOptions {
if #available(iOS 14.0, *) {
if .public == loadedStoreDescription.cloudKitContainerOptions?.databaseScope {
self._publicPersistentStore = container.persistentStoreCoordinator.persistentStore(for: loadedStoreDescription.url!)
} else if .private == loadedStoreDescription.cloudKitContainerOptions?.databaseScope {
self._privatePersistentStore = container.persistentStoreCoordinator.persistentStore(for: loadedStoreDescription.url!)
} else if .shared == cloudKitContainerOptions.databaseScope {
self._sharedPersistentStore = container.persistentStoreCoordinator.persistentStore(for: loadedStoreDescription.url!)
}
} else {
// Fallback on earlier versions
}
} /*else if appDelegate.testingEnabled {
if loadedStoreDescription.url!.lastPathComponent.hasSuffix("private.sqlite") {
self._privatePersistentStore = container.persistentStoreCoordinator.persistentStore(for: loadedStoreDescription.url!)
} else if loadedStoreDescription.url!.lastPathComponent.hasSuffix("shared.sqlite") {
self._sharedPersistentStore = container.persistentStoreCoordinator.persistentStore(for: loadedStoreDescription.url!)
}
}*/
})
container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
container.viewContext.transactionAuthor = appTransactionAuthorName
// Pin the viewContext to the current generation token, and set it to keep itself up to date with local changes.
container.viewContext.automaticallyMergesChangesFromParent = true
do {
try container.viewContext.setQueryGenerationFrom(.current)
} catch {
fatalError("###\(#function): Failed to pin viewContext to the current generation:\(error)")
}
#if DEBUG
do {
// Use the container to initialize the development schema.
try container.initializeCloudKitSchema(options: [])
} catch {
// Handle any errors.
fatalError("###\(#function): failed to load persistent stores: \(error)")
}
#endif
// Observe Core Data remote change notifications.
NotificationCenter.default.addObserver(self,
selector: #selector(storeRemoteChange(_:)),
name: .NSPersistentStoreRemoteChange,
object: container.persistentStoreCoordinator)
return container
}()
The very first time I run, Creates all the corresponding CD CKRecords in CloudKit public database _defaultZone. All values are copied from Core Data to CloudKit.
When the app is actively running I deleted a Core Data record and added a new record it did not delete it from Cloud Kit. Also when I add a new record in Core Data it did not export and add to Cloud Kit. When the app is actively running any changes I make are not exported and updated in Cloud Kit. What changes should I make to the code?
But when I run the app again then all the previous changes that I made when the app was active are updated. So looks like it does not perform live updates until the app is rerun again.
I get another error on the Debug Console "Custom zones are not allowed in public DB". I am not writing to custom DB. I wonder if this is preventing active updates?
oreData: error: CoreData+CloudKit: -[NSCloudKitMirroringDelegate _requestAbortedNotInitialized:](1983): <NSCloudKitMirroringDelegate: 0x2824d16c0> - Never successfully initialized and cannot execute request '<NSCloudKitMirroringExportRequest: 0x280a84780> FDB61E8D-658F-4C77-8615-EF07BAB72BAD' due to error: <CKError 0x28119ba20: "Partial Failure" (2/1011); "Failed to modify some records"; uuid = 6C66A151-DB59-4A1B-B3BD-02CFB9A4139C; container ID = "iCloud.com.greenendpoint.nr2r"; partial errors: {
B-63B7-45D2-BFE0-599972FB6FD7:(com.apple.coredata.cloudkit.zone:defaultOwner) = <CKError 0x2810e44e0: "Server Rejected Request" (15/2027); server message = "Custom zones are not allowed in public DB"; op = 23AFDAC55F70DC8D; uuid = 6C66A151-DB59-4A1B-B3BD-02CFB9A4139C>
Please help!
It worked. I had to delete my app on the test device and restart again. Looks like it recreated the data store and synced with Cloud Kit.

SwiftUI CloudKit Public Database with NSPersistentCloudKitContainer

Based on WWDC20 talk bellow:
https://developer.apple.com/videos/play/wwdc2020/10650/
The way to setup CloudKit Public Database with NSPersistentCloudKitContainer in "one line of code" is this:
description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey)
description.setOption(true as NSNumber, forKey:NSPersistentStoreRemoteChangeNotificationPostOptionKey)
description.cloudKitContainerOptions?.databaseScope = .public
How would that be on the new SwiftUI Persistent.swift template?
I tried the code bellow but didn't work:
import CoreData
struct PersistenceController {
static let shared = PersistenceController()
static var preview: PersistenceController = {
let result = PersistenceController(inMemory: true)
let viewContext = result.container.viewContext
for _ in 0..<10 {
let newItem = Item(context: viewContext)
newItem.timestamp = Date()
}
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
return result
}()
let container: NSPersistentCloudKitContainer
//This doesnt work
//container.cloudKitContainerOptions?.databaseScope = .public
init(inMemory: Bool = false) {
container = NSPersistentCloudKitContainer(name: "Market")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
}
}
guard let description = container.persistentStoreDescriptions.first else {
print("Can't set description")
fatalError("Error")
}
description.cloudKitContainerOptions?.databaseScope = .public

How to store a CloudKit CoreData instance in Shared Group Container?

If you need to share your core data with app extensions it can be useful to store the container in a shared group.
You have to get a description of the container and then set the URL:
let momdName = "MyModel"
guard let modelURL = Bundle(for: type(of: self)).url(forResource: momdName, withExtension:"momd") else {
fatalError("Error loading model from bundle")
}
guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
fatalError("Error initializing mom from: \(modelURL)")
}
guard let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.my-group")?.appendingPathComponent("My.sqlite") else {
fatalError("Cannot get shared group URL")
}
let container = NSPersistentCloudKitContainer(name: momdName, managedObjectModel: mom)
guard let description = container.persistentStoreDescriptions.first else {
fatalError("###\(#function): Failed to retrieve a persistent store description.")
}
description.url = containerURL
container.loadPersistentStores() { (storeDescription, error) in
if let error = error as NSError? {
// ...
}
}

Manual Core Data Requests in SwiftUI

Given that #FetchRequest does not support dynamic predicates (eg, I could not update the "month" in a calendar and re-query for the events I have scheduled in that month), I am trying to get a manual request to work.
The #FetchRequest already works if I don't try to make a dynamic predicate, so I assume the core data is configured to work correctly.
In my SceneDelegate I have:
guard let context = (UIApplication.shared.delegate as? AppDelegate)?.persistentContainer.viewContext else {
fatalError("Unable to read managed object context.")
}
let contentView = ContentView().environment(\.managedObjectContext, context)
and in my AppDelegate:
lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "Transactions")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
If I try doing a manual request in my ContentView like:
let employeesFetch = NSFetchRequest<NSFetchRequestResult>(entityName: "Employees")
do {
let employees = try managedObjectContext.fetch(employeesFetch) as! [Employees]
} catch {
fatalError("Failed to fetch employees: \(error)")
}
This fails because `Exception NSException * "+entityForName: nil is not a legal NSPersistentStoreCoordinator for searching for entity name 'Employees'"
What configuration am I missing?

Swift 3 preload from SQL files in appDelegate

I am attempting a swift 3 conversion. I was preloading data from sql files in my swift 2 project. I am unsure how to make this work in swift 3.0? Below is my swift 2 appDelegate file. In swift 3 the core data stack has changed enough, that I do not know where to try to reuse the same code that worked for me with swift 2. The code i was using that worked is listed under the comment "added for SQLite preload". Thank you
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "self.edu.SomeJunk" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "ESLdata", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("ESLdata.sqlite")
//ADDED FOR SQLITE PRELOAD
// Load the existing database
if !FileManager.default.fileExists(atPath: url.path) {
let sourceSqliteURLs = [Bundle.main.url(forResource: "ESLdata", withExtension: "sqlite")!,Bundle.main.url(forResource: "ESLdata", withExtension: "sqlite-wal")!, Bundle.main.url(forResource: "ESLdata", withExtension: "sqlite-shm")!]
let destSqliteURLs = [self.applicationDocumentsDirectory.appendingPathComponent("ESLdata.sqlite"), self.applicationDocumentsDirectory.appendingPathComponent("ESLdata.sqlite-wal"), self.applicationDocumentsDirectory.appendingPathComponent("ESLdata.sqlite-shm")]
for index in 0 ..< sourceSqliteURLs.count {
do {
try FileManager.default.copyItem(at: sourceSqliteURLs[index], to: destSqliteURLs[index])
} catch {
print(error)
}
}
}
// END OF ADDED CODE
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: [NSMigratePersistentStoresAutomaticallyOption:true, NSInferMappingModelAutomaticallyOption:true])
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
print("SAVED")
} catch {
print("Save Failed")
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
The following is what I attempted to update the code to, and had no luck:
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 = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "ESLdata")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
//ADDED FOR SQLITE PRELOAD
let url = self.getDocumentsDirectory().appendingPathComponent("ESLdata.sqlite")
// Load the existing database
if !FileManager.default.fileExists(atPath: url.path) {
let sourceSqliteURLs = [Bundle.main.url(forResource: "ESLdata", withExtension: "sqlite")!,Bundle.main.url(forResource: "ESLdata", withExtension: "sqlite-wal")!, Bundle.main.url(forResource: "ESLdata", withExtension: "sqlite-shm")!]
let destSqliteURLs = [self.getDocumentsDirectory().appendingPathComponent("ESLdata.sqlite"), self.getDocumentsDirectory().appendingPathComponent("ESLdata.sqlite-wal"), self.getDocumentsDirectory().appendingPathComponent("ESLdata.sqlite-shm")]
for index in 0 ..< sourceSqliteURLs.count {
do {
try FileManager.default.copyItem(at: sourceSqliteURLs[index], to: destSqliteURLs[index])
} catch {
print(error)
}
}
}
// END OF ADDED CODE
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
This seems to be the solution I was looking for. As far as I can tell so far, it works. And sticks the the new slimmer format core data stack for iOS10.
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
}()
First of all-- the changes you have made are only partly about Swift 3. You are not required to use NSPersistentContainer, and doing so is a completely different issue from using Swift 3. You can still use all the same Core Data classes and methods as in Swift 2, but with different syntax. If you understand your older code, you're probably better off keeping the same logic and classes but with newer syntax.
If you do switch to NSPersistentContainer, the loadPersistentStores method is more or less comparable to the addPersistentStore call in your older code. When you call that method, the persistent store file is loaded, so it must exist if you want to use its data. In your older code you copy your pre-loaded data before loading the persistent store, but in your newer code you're doing it afterward. That's why you're not seeing the data.
Since you appear to be using the same default store file name that NSPersistentContainer will assume, that's probably enough. If it still doesn't find the data, you may need to create an NSPersistentStoreDescription to tell your container where to put the store file.
But if I were you I'd stick with the older approach and the newer Swift 3 syntax.

Resources