Core data + CloudKit - sharing between iOS and watchOS companion app - core-data

In my app I store data with core data.
Recently I discovered the new feature introduced by Apple in WWDC19 which allows core data to work with CloudKit.
I just enabled cloudKit for my app and used an NSPersistentCloudKitContainer instead of NSPersistentContainer and all was set up ! All my data is shared between ios devices.
That works like NSPersistentContainer but it sends a copy of changes on icloud server, so there is always a local cache of data.
Now I'd like to access that data from my apple watch companion app but not all the data, only a specific entity!
So how could I do that?
I tried to set the NSPersistentCloudKitContainer shared between both targets with the attribut inspector but watch don't get any data. I can see in cloudKit dashboard there are requests from watchOS but watch just don't get any data.
But if I save an entity from the watch to core data I can get it only from the watch.
My conclusion is both are no storing the data at the same place. So how could I fix that? There are already using the same NSPersistendCloudKitContainer.
the container shared between both targets :
import Foundation
import CoreData
public class CoreDataContainer {
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 = NSPersistentCloudKitContainer(name: "MyProjectName")
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)")
}
}
}
}

Resolved by adding a cloudKitContainerOptions to my context description like this :
class CoreDataStack {
static let persistentContainer: NSPersistentCloudKitContainer = {
let container = NSPersistentCloudKitContainer(name: "MyProjectName")
let description = container.persistentStoreDescriptions.first
description?.cloudKitContainerOptions = NSPersistentCloudKitContainerOptions(containerIdentifier: "myCloudContainerID") // HERE !
container.loadPersistentStores(completionHandler: { (_, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
}

Related

Cocos2d-x Multithreading sceanrio crashes the game

my scenario is simple:i made a game using cocos2d-x and i want to download images (FB and Google play) for multi player users and show them once the download is done as texture for a button.
in ideal world, things work as expected.
things get tricky when those buttons got deleted before the download is done.
so the callback function is in weird state and then i get signal 11 (SIGSEGV), code 1 (SEGV_MAPERR)
and the app crashes
This is how i implmented it
I have a Layout class called PlayerIcon. the cpp looks like this
void PlayerIcon::setPlayer(string userName, string displayName, string avatarUrl){
try {
//some code here
downloadAvatar(_userName, _avatarUrl);
//some code here
}
catch(... ){
}
}
void PlayerIcon::downloadAvatar(std::string _avatarFilePath,std::string url) {
if(!isFileExist(_avatarFilePath)) {
try {
auto downloader = new Downloader();
downloader->onFileTaskSuccess=CC_CALLBACK_1(PlayerIcon::on_download_success,this);
downloader->onTaskError=[&](const network::DownloadTask& task,int errorCode,
int errorCodeInternal,
const std::string& errorStr){
log("error while saving image");
};
downloader->createDownloadFileTask(url,_avatarFilePath,_avatarFilePath);
}
catch (exception e)
{
log("error while saving image: test");
}
} else {
//set texture for button
}
}
void PlayerIcon::on_download_success(const network::DownloadTask& task){
_isDownloading = false;
Director::getInstance()->getScheduler()-> performFunctionInCocosThread(CC_CALLBACK_0(PlayerIcon::reload_avatar,this));
}
void PlayerIcon::reload_avatar(){
try {
// setting texture in UI thread
}
catch (...) {
log("error updating avatar");
}
}
As i said, things works fine until PlayerIcon is deleted before the download is done.
i dont know what happens when the call back of the download task point to a method of un object that s deleted (or flagged for deletion).
i looked in the downloader implementation and it doesn't provide any cancellation mechanism
and i'm not sure how to handle this
Also, is it normal to have 10% crash rate on google console for a cocos2dx game
any help is really appreciated
Do you delete de Downloader in de destructor of the PlayerIcon?
there is a destroy in the apple implementation witch is trigered by the destructor.
-(void)doDestroy
{
// cancel all download task
NSEnumerator * enumeratorKey = [self.taskDict keyEnumerator];
for (NSURLSessionDownloadTask *task in enumeratorKey)
{
....
DownloaderApple::~DownloaderApple()
{
DeclareDownloaderImplVar;
[impl doDestroy];
DLLOG("Destruct DownloaderApple %p", this);
}
In the demo code of cocos2d-x: DownloaderTest.cpp they use:
std::unique_ptr<network::Downloader> downloader;
downloader.reset(new cocos2d::network::Downloader());
instead of:
auto downloader = new Downloader();
It looks like you are building this network code as part of your scene tree. If you do a replaceScene/popScene...() call, while the async network software is running in the background, this will cause the callback to disappear (the scene will be deleted from the scene-stack) and you will get a SEGFAULT from this.
If this is the way you've coded it, then you might want to extract the network code to a global object (singleton) where you queue the requests and then grab them off the internet saving the results in the global-object's output queue (or their name and location) and then let the scene code check to see if the avatar has been received yet by inquiring on the global-object and loading the avatar sprite at this point.
Note, this may be an intermittent problem which depends on the speed of your machine and the network so it may not be triggered consistently.
Another solution ...
Or you could just set your function pointers to nullptr in your PlayerIcon::~PlayerIcon() (destructor):
downloader->setOnFileTaskSuccess(nullptr);
downloader->setOnTaskProgress(nullptr);
Then there will be no attempt to call your callback functions and the SEGFAULT will be avoided (Hopefully).

managedObjectContext in Swift 3

I want to work through this example code in which Swift and CoreData is used to create a table. However, using Swift 3 I fail to get it to work. Most importantly, I cannot properly replace the line
// set up the NSManagedObjectContext
let appDelegate = NSApplication.sharedApplication().delegate as! AppDelegate
managedContext = appDelegate.managedObjectContext
even though I found this related question (which however is iOS not OS X). How can I replace that piece of code which produces the error message Value of type 'AppDelegate' has no member 'managedContext'?
Swift 3 in macOS
let appDelegate = NSApplication.shared().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
The error you provided says 'AppDelegate' has no member 'managedContext' instead of 'AppDelegate' has no member 'managedObjectContext', which would lead me to assume you just need to fix your syntax.
Swift 3 in iOS 10
Core Data needs at least 3 things to work:
A managed object model
A persistent store coordinator
And a managed object context
Put those three things together and you get the Core Data Stack.
When iOS 10 came out, a new object was introduced called the NSPersistentContainer which encapsulates the core data stack.
How to create the container object is answered here.
managedObjectContext is now a property called viewContext, accessed via:
let delegate = UIApplication.shared.delegate as! AppDelegate
let managedObjectContext = delegate.persistentContainer.viewContext
A helpful article is What's New in Core Data, but if that reading seems a little too heavy, this WWDC video does a great job of explaining this topic.
AppDelegate has below members only
// 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: "")
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
}()
so use
let managedContext = (UIApplication.shared.delegate as! appDelegate).persistentContainer.viewContext
This will work fine
For macOS and Swift 3.1
let moc: NSManagedObjectContext = (NSApplication.shared().delegate as! AppDelegate).persistentContainer.viewContext
I swift 3 you can get managedContext set by this code:
let managedContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

Navigation problems with MVVMLight

I'm having a couple of issues when trying to navigate using MVVMLight.
On iOS, I have created my NavigationService in AppDelegate/FinishedLoading with the following code
var nav = new NavigationService();
nav.Configure(ViewModelLocator.MainPageKey, "MainPage");
nav.Configure(ViewModelLocator.MapPageKey, "MapPage");
// iOS uses the UINavigtionController to move between pages, so will we
nav.Initialize(Window.RootViewController as UINavigationController);
// finally register the service with SimpleIoc
SimpleIoc.Default.Register<INavigationService>(() => nav);
When I use NavigateTo to move between the two pages, I continually get the same error asking if I have called NavigationService.Initialize. Obviously I have. The first ViewController shows without a problem.
On Android, I'm having issues again with the second Activity, but with a different error.
I am passing a List< double> as the object parameter in NavigateTo and then in the Activity, use the following to retrieve the passed object
void GetDataFromViewModel()
{
var NavService = (NavigationService)SimpleIoc.Default.GetInstance<INavigationService>();
var data = NavService.GetAndRemoveParameter<object>(Intent) as List<double>;
if (data != null)
{
ViewModel.Latitude = data[0];
ViewModel.Longitude = data[1];
}
}
Problem is that straight after the base.OnCreate in my OnCreate method, the app crashes out with the error
UNHANDLED EXCEPTION:
[MonoDroid] System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Microsoft.Practices.ServiceLocation.ActivationException: Type not found in cache: System.Object.
My NavigateTo line looks like this
INavigationService navigationService;
...code
navigationService.NavigateTo(ViewModelLocator.MapPageKey, new List<double> { Latitude, Longitude });
This has got me stumped!

How to resolve: "NSPersistentStoreCoordinator has no persistent stores"?

I'm following this tutorial exactly, which adds CoreData to an existing app:
https://www.youtube.com/watch?v=WcQkBYu86h8
When I get to the seedPerson() moc.save(), the app crashes with this error:
CoreData: error: Illegal attempt to save to a file that was never
opened. "This NSPersistentStoreCoordinator has no persistent stores
(unknown). It cannot perform a save operation.". No last error
recorded.
The NSManagedSubclass has been added.
The DataController is wired up and I can step into it. It isn't until the save() that things go wrong. Any idea what I might have left out to cause this error?
I also followed that YouTube tutorial and had the same problem. I just removed the background thread block that adds the persistent store and it worked. Here's my DataController:
import UIKit
import CoreData
class WellbetDataController: NSObject {
var managedObjectContext: NSManagedObjectContext
override init() {
// This resource is the same name as your xcdatamodeld contained in your project.
guard let modelURL = NSBundle.mainBundle().URLForResource("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(contentsOfURL: modelURL) else {
fatalError("Error initializing mom from: \(modelURL)")
}
let psc = NSPersistentStoreCoordinator(managedObjectModel: mom)
self.managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
self.managedObjectContext.persistentStoreCoordinator = psc
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
let docURL = urls[urls.endIndex-1]
/* The directory the application uses to store the Core Data store file.
This code uses a file named "DataModel.sqlite" in the application's documents directory.
*/
let storeURL = docURL.URLByAppendingPathComponent("DataModel.sqlite")
do {
try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
} catch {
fatalError("Error migrating store: \(error)")
}
// dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
// let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
// let docURL = urls[urls.endIndex-1]
// /* The directory the application uses to store the Core Data store file.
// This code uses a file named "DataModel.sqlite" in the application's documents directory.
// */
// let storeURL = docURL.URLByAppendingPathComponent("DataModel.sqlite")
// do {
// try psc.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
// } catch {
// fatalError("Error migrating store: \(error)")
// }
// }
}
}
Unfortunately, that video uses some code from Apple's website, and that code example is flawed. The main flaw is that it caches the MOC before the persistent store has been added to the MOC. Thus, if the creation of the store fails at all, the managed object context will be initialized with a persistent store coordinator that has no store.
You need use the debugger and step through the code that creates the PSC (the DataController.init method) and see why the failure happens. If you cut/paste the same way as in that example, then maybe you also forgot to change the name of your model when instantiating the model.
In any event, the most likely cause is that some initialization code in that function failed, and you are subsequently going happily along with a core data stack that has no stores.
You need to load the persistent stores
let persistentContainer = NSPersistentContainer(name: "DbName")
persistentContainer.loadPersistentStores() { [weak self] _, error in
self?.persistentContainer.viewContext.automaticallyMergesChangesFromParent = true
}
The problem is on these two lines:
guard let modelURL = NSBundle.mainBundle().URLForResource("DataModel", withExtension:"momd") else {
&&
let storeURL = docURL.URLByAppendingPathComponent("DataModel.sqlite")
DataModel needs to be changed to the name of your application if your CoreData was created automatically by Xcode. Look for these lines in AppDelegate.swift
If this is the first time that you run the application after you put the core data in it then maybe it could work by removing the app from simulator and run it again.
It was happened to me and it works after I did that.

Is it safe to pass NSManagedObject(created in main context) from a background thread to the main thread?

I am using AFNetworking to parse some data and then save to CoreData, I want to do something like this.
let parserContext: NSManagedObjectContext = MTCoreDataManager.sharedManager().newPrivateManagedObjectContext()
let mainContext: NSManagedObjectContext = MTCoreDataManager.sharedManager().managedObjectContext()
override func responseObjectForResponse(response: NSURLResponse!, data: NSData!, error: NSErrorPointer) -> AnyObject? {
var model: NSManagedObject?
parserContext.performBlockAndWait {
....parsing data...
....create model and assign value...
....save model...
let objID = model.objectID
mainContext.performBlockAndWait {
model = mainContext.objectWithID(objID)
}
}
return model
}
let op = AF.GET(path, parameters: nil, success: { (operation: AFHTTPRequestOperation, response: AnyObject) -> Void in
// main thread
println(response)
}) { (operation: AFHTTPRequestOperation, error: NSError) -> Void in
println(error.description)
}
As responseObjectForResponse runs in a background thread, I want to use a background context to parse the data and create the NSManagedObject in that context, and then get back the object in main thread as the final callback will be on the main thread, I don't want to return the NSManagedObjectID, I want to return the NSManagedObject but I don't know if this is safe.
Is it safe? I don't think it is.
Instead you should create a child context in the completion block and do all your Core Data saving within a block.
childContext.performBlockAndWait() {
// parse, insert and save
}
Remember that saving will just "push" the changes up to the main context. You will still have to save them to the persistent store. The main context should be aware of any changes automatically (via a NSFetchedResultsControllerDelegate or NSNotificationCenter).
I have an additional convenience method in my data manager class (or app delegate) to save the data to the persistent store, similar to the plain vanilla saveContext method provided by the Apple templates. This should a method that can be called safely from anywhere by also using above block API to save the context.

Resources