Coredata in ios keyboard extension - ios

I read below github page and used the code for sharing coredata between my ios Keyboard Extension and the app.
https://github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups
The code is working right on the simulator but it is not working but addPersistentStore not working on real device:
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return 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
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let directory = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier:"group.testKeyboard.asanpardakht.ir")!
let url = directory.appendingPathComponent("AsanPardakhtSharedData.sqlite")
do {
try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch var error as NSError {
coordinator = nil
NSLog("Unresolved error \(error), \(error.userInfo)")
abort()
} catch {
fatalError()
}
print("\(String(describing: coordinator?.persistentStores))")
return coordinator
}()
I get below errors:
NSError domain: "NSCocoaErrorDomain" - code: 512
"reason" : "Failed to create file; code = 1"
I tried setting RequestOpenAccess to YES in my info.plist file but it is not still working. Does someone has any idead about the problem?

I figured out that below post works right for keyboard extension too:
https://github.com/maximbilan/iOS-Shared-CoreData-Storage-for-App-Groups
The only problem is that for keyboard extension we should also set RequestOpenAccess at info.plist to YES.
When set it to YES in the setting of the keyboard an option appears for the Full Access we should turn it On and then the code also works on real device.
Developers should make sure that before calling the method in the quest ask user to turn the option to On.

Related

How to add Core Data to existing Xcode 9 Swift 4 iOS 11 project?

An update is requested, since this question has of course been answered for previous versions, the latest search result dated 12/16 generates irrelevant compatibility with previous iOS 9 and 10 projects.
The documentation of course says to select the Use Core Data checkbox when starting a new project, which I did not select, but now think iCloud + Core Data needs to be added to take my app to its next phase -> wherein something like NSFileCoordinator and NSFilePresenter is needed, since in my app UI users are presented with a number of TOPICS, each having three OPTIONS, regarding which users are to choose one option. For each topic the UI then displays the TOTAL NUMBER of users who have chosen each option and the PERCENTAGE of the total for each option.
Right now, the number of choices for each option and the percentage of the total are of course just calculated in my native app -> but actually need to be CALCULATED in something central like the cloud or most likely on a website…but then the website raises the simultaneous read/write problems that NSFileCoordinator and NSFilePresenter have already solved.
So if the iCloud + Core Data system can interject basic arithmetic calculations on the existing Ubiquitous Container numerical value totals - in the cloud upon receiving write numerical value commands from individual users - before sending out the new Ubiquitous Container numerical total and percent values - then I’d much appreciate advise on how fix the errors generated below in trying Create and Initialize the Core Data Stack. Otherwise guess I’ll have to scrape Xcode and go to a hybrid app like PhoneGap if that's the best one for the job.
Hence, referring to the Core Data Programming Guide:
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/InitializingtheCoreDataStack.html#//apple_ref/doc/uid/TP40001075-CH4-SW1
and pasting in the following code in the beginning of my existing project, generates
Use of unresolved identifier ‘persistentContainer’… ‘managedObjectContext’
... errors. And the line
init(completionClosure: #escaping () -> ()) {
... generates
Initializers may only be declared within a type
import UIKit
import CoreData
class DataController: NSObject {
var managedObjectContext: NSManagedObjectContext
init(completionClosure: #escaping () -> ()) {
persistentContainer = NSPersistentContainer(name: "DataModel")
persistentContainer.loadPersistentStores() { (description, error) in
if let error = error {
fatalError("Failed to load Core Data stack: \(error)")
}
completionClosure()
}
}
}
init(completionClosure: #escaping () -> ()) {
//This resource is the same name as your xcdatamodeld contained in your project
guard let modelURL = Bundle.main.url(forResource: "DataModel", withExtension:"momd") else {
fatalError("Error loading model from bundle")
}
// The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
guard let mom = NSManagedObjectModel(contentsOf: modelURL) else {
fatalError("Error initializing mom from: \(modelURL)")
}
let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = psc
let queue = DispatchQueue.global(qos: DispatchQoS.QoSClass.background)
queue.async {
guard let docURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
fatalError("Unable to resolve document directory")
}
let storeURL = docURL.appendingPathComponent("DataModel.sqlite")
do {
try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: storeURL, options: nil)
//The callback block is expected to complete the User Interface and therefore should be presented back on the main queue so that the user interface does not need to be concerned with which queue this call is coming from.
DispatchQueue.main.sync(execute: completionClosure)
} catch {
fatalError("Error migrating store: \(error)")
}
}
}
// followed by my existing working code:
class ViewController: UIViewController {
go to File > new file... select core Data under iOS and select Data Model
you'll still need some code which xcode auto generates whenever you select core data during project creation.
to get it, just create new project with core data option checked and copy all the code written under ** //Mark: - Core Data Stack** comment in AppDelegate.swift
and add
import CoreData
above
OPTIONAL
And don't forget to change the name of the app after copying the completion block for lazy var persistentContainer. Change the name of your app on this part *NSPersistentContainer(name: "SHOULD-BE-THE-NAME-OF-YOUR-APP") And managedObjectModel function of the code you just copied**
If you're lazy like me, here's all the code you need to copy from the new Core Data project... (why make everyone create a new project?). Change YOUR_APP_NAME_HERE
At the top of your AppDelegate.swift file:
import CoreData
At the bottom of AppDelegate.swift file, before the ending curly bracket:
// MARK: - Core Data stack
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
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: "YOUR_APP_NAME_HERE")
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)")
}
})
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)")
}
}
}
I know this is answered, but I believe the actual problem is with Apple's Documentation. If you compare the Objective-C code to the Swift code, you will see that var managedObjectContext: NSManagedObjectContext is not actually defined. You should replace that line with var persistentContainer: NSPersistentContainer. This is the Objective-c interface
#interface MyDataController : NSObject
#property (strong, nonatomic, readonly) NSPersistentContainer *persistentContainer;
- (id)initWithCompletionBlock:(CallbackBlock)callback;
#end
So DataController.swift should be:
class DataController: NSObject {
// Delete this line var managedObjectContext: NSManagedObjectContext
var persistentContainer: NSPersistentContainer
init(completionClosure: #escaping () -> ()) {
persistentContainer = NSPersistentContainer(name: "DataModel")
persistentContainer.loadPersistentStores() { (description, error) in
if let error = error {
fatalError("Failed to load Core Data stack: \(error)")
}
completionClosure()
}
}
}
As for the rest of your code, it's not necessary Apple Docs.
Prior to iOS 10 and macOS 10.12, the creation of the Core Data stack was more involved
That section of code is showing you the old way.
Use the following code
lazy var persistantCoordinator :NSPersistentStoreCoordinator = {
let poc = NSPersistentStoreCoordinator(managedObjectModel:managedObjectModel)
let documentFolderUrl = FileManager.default.urls(for: .documentDirectory, in:.userDomainMask).last
let path = documentFolderUrl!.appendingPathComponent("Database.sqlite")
let options = [NSMigratePersistentStoresAutomaticallyOption: true,NSInferMappingModelAutomaticallyOption: true]
do{
try poc.addPersistentStore(ofType:NSSQLiteStoreType, configurationName: nil, at: path, options: options)
}catch{
print(error.localizedDescription)
}
return poc
}()
private lazy var managedObjectModel:NSManagedObjectModel = {
let url = Bundle.main.url(forResource:"Database", withExtension:"momd")
return NSManagedObjectModel(contentsOf:url!)!
}()
fileprivate lazy var managedObjectContext:NSManagedObjectContext = {
let moc = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
moc.persistentStoreCoordinator = persistantCoordinator
return moc
}()

How to add NSManagedObjectContext with ConcerrencyType in swift 3?

In my app i have tasks that download data and save them to CoreData. After i migrated to swift 3 it started throwing exceptions while saving data, at a random time. As i understood, it can happen if i use one context for all operations. Now i created another context with concurrency type, everything works without errors, but nothing is saved to .sqlite file :)
Here's how i create context:
static let context : NSManagedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
static let privateContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.privateQueueConcurrencyType)
static func declare()
{
AixmParser.privateContext.parent = AixmParser.context
}
I save data like this:
do{
try privateContext.save()
}
catch{
}
Do i have to add something to declaration or to the core data stack?
Update: Core Data stack below.
// 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: "AppName")
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)")
}
container.viewContext.perform({
// actions upon the NSMainQueueConcurrencyType NSManagedObjectContext for this container
})
})
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)")
}
}
}
So first is that you have to create a link from the privateContext to the NSPersistentContainer's viewContext. So, while creating the private,
privateContext, privateContext.parentContext = viewContext. While saving
let context = privateContext
while(context != nil) {
context.save()
context = context.privateContext
}
This will work.
I am not sure why did you get the errors in the first place.

Core Data error code=134030 "An error occurred while saving" with no userInfo

I have an app built in Swift 3 using Xcode 8 GM seed. The app has a keyboard extension. I'm using the shared group directory for the sqlite db location, and database access is done using a framework. Things are working until I try to call SaveContext() from the keyboard. I get the error mentioned in the title error code=134030. The message says "An error occurred while saving" and there is no additional information. There's no userInfo for me to get at the underlying error.
I've dumped out some debug information to make sure I'm looking at the same instance of the same item that I'm trying to update. It's a very simple update, just incrementing a use counter when something is used. Is there some problem with saving from a keyboard extension? Do they open in read-only mode?
Here's the bulk of the CoreDataStack:
let coreDataStack = CoreDataStack()
public class CoreDataStack {
public func saveContext()
{
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch let error {
// 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)")
}
}
}
// MARK: - Private
lazy var managedObjectContext: NSManagedObjectContext = {
return self.persistentContainer.viewContext
}()
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 modelUrl = Bundle(identifier: "com.myapp.AppDataKit")?.url(forResource: "MyApp-SE", withExtension: "momd")
let managedObjectModel = NSManagedObjectModel(contentsOf: modelUrl!)!
let container = NSPersistentContainer(name: "MyApp-SE", managedObjectModel: managedObjectModel)
container.persistentStoreDescriptions = [NSPersistentStoreDescription(url: try! FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.myapp")!.appendingPathComponent("MyAppSEData.sqlite"))]
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)")
}
})
return container
}()
} // class CoreDataStack
In the catch I'm examining error and I can't get any more info from it. After casting it to NSError it still doesn't help since userInfo is an empty dict.
I haven't implemented the error handling as yet, but I can see the items in the keyboard so there's no issues with the retrieval. Only when saving does it crash.
The place where I'm attempting the update is ridiculously simple:
item.useCount = NSNumber(value: item.useCount.intValue + 1)
Logger.add(item.debugDescription)
AppData.SaveContext()
AppData is a class with static functions to access core data
public class AppData {
public static func SaveContext() {
coreDataStack.saveContext()
}
...
}
I looked at the device log and didn't get any better information there. I can see the two lines in my data kit and then two from libswiftCore.dylib
0 libswiftCore.dylib 0x0000000100ab2848 0x100a80000 + 206920
1 libswiftCore.dylib 0x0000000100ab2848 0x100a80000 + 206920
Anyone know how to symbolicate libswiftcore in Xcode8?
Thanks,
Mike
I figured it out. Turns out that it was because the "Allow Full Access" option for the keyboard was turned off. So if you want to be able to write to the shared group folder, including updating a sqlite db, you have to install the app & keyboard and check the "Allow Full Access" option first. Then you can return to Xcode and run the extension in debug mode. The setting is retained and everything should work.
Mike

Tabbed Application and Core Data functions in AppDelegate Swift

I am a newbie in Swift and iPhone apps. Recently I created a project with Tabbed Application. As I have already finished my project, the last step was to add core data to save my info. I decided to create a new Single View Application with core data and copy its core data functions from Single View Application AppDelegate to Tabbed Application AppDelegate.
Here is the code I copied (from Single View Application to Tabbed Application, AppDelegate.swift):
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.Spookas.bandymas" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .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 = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: 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.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
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()
} catch {
// Replace this implementation 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.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
There are no errors in the code when I write it; however, when I start an application and do any methods that should save the data, I get this error:
2016-06-15 10:55:19.182 Taupyk![1387:32488] CoreData: Failed to load
NSManagedObjectModel with URL
'file:///Users/MyMac/Library/Developer/CoreSimulator/Devices/029E41C4-9E00-474A-BBA1-410D1211D39F/data/Containers/Bundle/Application/FE7605D7-A2F3-449E-8961-F0B33FCB4D15/Taupyk!.app/Model.momd/'
fatal error: unexpectedly found nil while unwrapping an Optional value
It then points into these lines of code:
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 = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
It says something about Thread 1: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0)
I have also copied data model from the single view app project and renamed it into "Model", yet it still throws an error
I saw there were other people like me, however, they were able to resolve the issue whereas I can not and don't understand why it is not working even though I have done the same thing
Thanks for your help in advance
You are missing the actual CoreData database.
Add a new file to your project
select CoreData
Select Data Model
Call your data model "Model" (to match your source code)
Note, you will see this in your single view project as well.
Select new file to your project.
2.core Data -> Data model->click next button - >click create button.
your project model Add Entity and entity name.

iOS 9 CoreData / ICloud - No such document at URL

UPDATE 2
I am also occasionally getting this error:
CoreData: Ubiquity: Librarian returned a serious error for starting downloads Error Domain=BRCloudDocsErrorDomain Code=6
I am wondering if it is related? Am working on submitting a bug report but would appreciate any insight.
UPDATE
When this error occurs I am getting very strange behavior with coredata where it will not be able to find related objects in the same context. This is absolutely crippling my app now
ORIGINAL QUESTION
I have an app that seems to work perfectly 90% of the time syncing CoreData with iCloud Ubiquitous storage.
Sometimes I receive this error and things start going a little crazy:
CoreData: Ubiquity: Librarian returned a serious error for starting downloads Error Domain=BRCloudDocsErrorDomain Code=5 "No document at URL"
I have searched to find information about how to fix this, but I am not seeing anything to help me in the other questions that have been posted. Many people simply stating that they just gave up trying to fix it.
Can anyone see any issues with my core data stack that would cause this?! I feel like im taking crazy pills.
// MARK: - Core Data stack
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 = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return 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
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last as NSURL!
let storeURL = documentsDirectory.URLByAppendingPathComponent("ArrivedAlive.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
let storeOptions = [NSPersistentStoreUbiquitousContentNameKey: "ArrivedAliveStore", NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: storeOptions)
} catch var error1 as NSError {
error = error1
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = 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 \(error), \(error!.userInfo)")
abort()
} catch {
fatalError()
}
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
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
For those of you out there struggling with these issues - let me give you some good news:
To solve the problem follow these steps:
Download and implement the Ensembles GitHub
Add very small amount of code to your appDelegate to create and manage the ensemble object
Cry out your pent up frustration - you are done.
IT FIXED ALL CLOUD SYNCING ERRORS
It just works like magic and I couldn't be happier. It essentially works like a middle man between core data and iCloud to make sure nobody has a seizure mid thought.

Resources