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.
Related
I'm just learning Core Data and I need to implement Core Datafor both iOS 9 and iOS 10 as my only iPad test device is an iPad3 running iOS 9.3.5. I'm trying to follow this solution https://charleswilson.blog/2016/09/09/out-of-context-using-core-data-on-ios-9-3-and-10-0/ ( not sure I could paste the whole code from the link ) as I failed with implementing other solutions from stack overflow. I'm not sure If I got this one thing right: Inside the lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator there is this let modelURL = Bundle.main.url(forResource: modelName, withExtension: modelExtension)! that I see in other solutions here in stack overflow and they're all declared as with different Stringvalues for forResource parameter, but all with the same "momd"value for withExtension: parameter. I actually thought the since I'm using an .xcdatamodeld I should put in my data model name for forResource parameter and "xcdatamodeld" for withExtension: parameter, resulting in my case as :
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let url = self.applicationDocumentsDirectory.appendingPathComponent("fix_it_shop").appendingPathExtension("xcdatamodeld")
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
let dict : [String : Any] = [NSLocalizedDescriptionKey : "Failed to initialize the application's saved data" as NSString,
NSLocalizedFailureReasonErrorKey : "There was an error creating or loading the application's saved data." as NSString,
NSUnderlyingErrorKey : error as NSError]
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
fatalError("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
}
return coordinator
}()
Is it so or withExtension: parameter is unrelated to my xcdatamodeld file extension and I should use "momd" instead? Similar questions I found point me in both directions. Many thanks for any explanation you could give about it.
You should use “momd” as the file extension for the model. During the Xcode compilation process, your .xcdatamodeld file gets compiled into a .momd file, which is what actually gets included in the bundle.
However, the url variable in the persistentStoreCoordinator definition refers to the NSPersistentStore file, which for a sqlite store will have the extension “.sqlite”.
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.
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
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.
As mentioned in WWDC 2014 session 225 (Whatʼs New in Core Data), Core Data on iOS 8 and OS X Yosemite now support the command line argument -com.apple.CoreData.ConcurrencyDebug 1 to enable assertions that detect violations of Core Dataʼs concurrency contract.
In my experiments with this, I have found that it works under iOS 8 beta 1 (both on the device and in the simulator), but I seem to have found a false positive, i.e. the framework is throwing a multithreading violation exception where it should not do so. At least that's what I believe.
Question: is the code below correct or am I doing something that violates Core Dataʼs threading model?
What I do is set up a very simple Core Data stack (with an in-memory store, for simplicity's sake) with a managed object context named backgroundContext with private queue concurrency. I then invoke performBlockAndWait { } on that context and in the block I create a new managed object, insert it into the context, and save.
The save operation is where I get the multithreading violation exception from Core Data.
var backgroundContext: NSManagedObjectContext?
func setupCoreDataStackAndViolateThreadingContract()
{
let objectModelURL = NSBundle.mainBundle().URLForResource("CoreDataDebugging", withExtension: "momd")
let objectModel: NSManagedObjectModel? = NSManagedObjectModel(contentsOfURL: objectModelURL)
assert(objectModel)
// Set up a simple in-memory Store (without error handling)
let storeCoordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: objectModel)
assert(storeCoordinator)
let store: NSPersistentStore? = storeCoordinator!.addPersistentStoreWithType(NSInMemoryStoreType, configuration: nil, URL: nil, options: nil, error: nil)
assert(store)
// Set up a managed object context with private queue concurrency
backgroundContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
assert(backgroundContext)
backgroundContext!.persistentStoreCoordinator = storeCoordinator!
// Work on the background context by using performBlock:
// This should work but throws a multithreading violation exception on
// self.backgroundContext!.save(&potentialSaveError)
backgroundContext!.performBlockAndWait {
NSEntityDescription.insertNewObjectForEntityForName("Person", inManagedObjectContext: self.backgroundContext!) as NSManagedObject
person.setValue("John Appleseed", forKey: "name")
var potentialSaveError: NSError?
// In the following line: EXC_BAD_INSTRUCTION in
// `+[NSManagedObjectContext __Multithreading_Violation_AllThatIsLeftToUsIsHonor__]:
let didSave = self.backgroundContext!.save(&potentialSaveError)
if (didSave) {
println("Saving successful")
} else {
let saveError = potentialSaveError!
println("Saving failed with error: \(saveError)")
}
}
}
I have tested essentially the same code in Objective-C and got the same result so I doubt it is a Swift problem.
Edit: If you want to run the code yourself, I have put a project on GitHub (requires Xcode 6/iOS 8 beta).
Apple confirmed this as a bug. It has been fixed with Xcode 6 beta 4.