Comment synchroniser les données entre deux périphériques en utilisant Core Data & iCloud?

ce que j'essaie de réaliser c'est quand l'utilisateur crée, modifie ou supprime des données sur le persistent store il sera synchronisé avec le iCloud store puis mettre à jour les autres périphériques connectés dans le même compte iCloud.

j'ai créé un Core Data Stack en utilisant les ressources de L'Objectif C et en essayant D'écrire les miennes dans Swift, mais j'ai des problèmes de synchronisation des données en utilisant deux appareils connectés dans le même compte iCloud.

Par exemple quand iDevice A est connecté dans iCloud il sera sauvegarder les données sur iCloud mais quand iDevice B journaux dans iCloud, l'app supprime toutes les données déjà sur le stockage persistant pour enregistrer le iCloud sauvegarder, et tous les changements entre le magasin des appareils n'apparaît pas sur l'autre, mais semblent enregistrer à l'iCloud store la dernière sauvegarde, donc si l'application est supprimé et réinstallé, je vois la dernière sauvegarde effectuée par l'autre appareil, avec cela à l'esprit, si iDevice B était déjà connecté, il n'utiliserait pas les données de iDevice A sauf si l'application a été réinstallé et la dernière sauvegarde a été faite par l'autre appareil.

quelqu'un sait où je vais mal dans le Core data stack pour synchroniser les données entre deux appareils utilisant le même compte iCloud ?

Pile De Données De Base:

// MARK: - Core Data stack
// All the following code is in my appDelgate Core data stack 

func observeCloudActions(persistentStoreCoordinator psc:      NSPersistentStoreCoordinator?) {
// Register iCloud notifications observers for;

//Stores Will change 
//Stores Did Change 
//persistentStoreDidImportUbiquitousContentChanges
//mergeChanges

}

//Functions for notifications

func mergeChanges(notification: NSNotification) {
NSLog("mergeChanges notif:(notification)")
if let moc = managedObjectContext {
    moc.performBlock {
        moc.mergeChangesFromContextDidSaveNotification(notification)
        self.postRefetchDatabaseNotification()
    }
 }
}

  func persistentStoreDidImportUbiquitousContentChanges(notification: NSNotification) {
self.mergeChanges(notification);
 }    

func storesWillChange(notification: NSNotification) {
NSLog("storesWillChange notif:(notification)");
if let moc = self.managedObjectContext {
    moc.performBlockAndWait {
        var error: NSError? = nil;
        if moc.hasChanges && !moc.save(&error) {
            NSLog("Save error: (error)");
        } else {
            // drop any managed objects
        }
        moc.reset();
    }

       NSNotificationCenter.defaultCenter().postNotificationName("storeWillChange", object: nil)

 }
}

 func storesDidChange(notification: NSNotification) {
NSLog("storesDidChange posting notif");
self.postRefetchDatabaseNotification();
//Sends notification to view controllers to reload data      NSNotificationCenter.defaultCenter().postNotificationName("storeDidChange", object: nil)

 }

func postRefetchDatabaseNotification() {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
          NSNotificationCenter.defaultCenter().postNotificationName("storeDidChange", object: nil)

 })
 }


// 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 "hyouuu.pendo" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as! NSURL
}()

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("AppName", withExtension: "momd")!
NSLog("modelURL:(modelURL)")
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("CoreData.sqlite")

NSLog("storeURL:(storeURL)")

let storeOptions = [NSPersistentStoreUbiquitousContentNameKey:"AppStore"]

var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."

if coordinator!.addPersistentStoreWithType(
    NSSQLiteStoreType,
    configuration: nil,
    URL: storeURL,
    options: storeOptions,
    error: &error) == nil
{
    coordinator = nil
    // Report any error we got.
    let dict = NSMutableDictionary()
    dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
    dict[NSLocalizedFailureReasonErrorKey] = failureReason
    dict[NSUnderlyingErrorKey] = error
    error = NSError(domain: "Pendo_Error_Domain", code: 9999, userInfo: dict as [NSObject : AnyObject])
    // 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("AddPersistentStore error (error), (error!.userInfo)")
}

self.observeCloudActions(persistentStoreCoordinator: coordinator)

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
}()
15
demandé sur RileyDev 2015-08-15 00:05:47

2 réponses

C'est comme ça que j'ai ma configuration et qu'elle synchronise mes données de base et qu'elle maintient les changements synchronisés.

enter image description here

ceci vient de mon AppDelegate.

    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 url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("APPNAME.sqlite")
    var error: NSError? = nil
    var failureReason = "There was an error creating or loading the application's saved data."
    // iCloud store
    var storeOptions = [NSPersistentStoreUbiquitousContentNameKey : "APPNAMEStore",NSMigratePersistentStoresAutomaticallyOption: true,
        NSInferMappingModelAutomaticallyOption: true]
    // iCloud storeOptions need to be added to the if statement
    do {
        try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: NSURL.fileURLWithPath(url.path!), 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
}()

    // MARK: - iCloud
// This handles the updates to the data via iCLoud updates

func registerCoordinatorForStoreNotifications (coordinator : NSPersistentStoreCoordinator) {
    let nc : NSNotificationCenter = NSNotificationCenter.defaultCenter();

    nc.addObserver(self, selector: "handleStoresWillChange:",
        name: NSPersistentStoreCoordinatorStoresWillChangeNotification,
        object: coordinator)

    nc.addObserver(self, selector: "handleStoresDidChange:",
        name: NSPersistentStoreCoordinatorStoresDidChangeNotification,
        object: coordinator)

    nc.addObserver(self, selector: "handleStoresWillRemove:",
        name: NSPersistentStoreCoordinatorWillRemoveStoreNotification,
        object: coordinator)

    nc.addObserver(self, selector: "handleStoreChangedUbiquitousContent:",
        name: NSPersistentStoreDidImportUbiquitousContentChangesNotification,
        object: coordinator)
}
2
répondu MwcsMac 2015-09-02 20:07:38

une différence que je vois entre ce qui fonctionne pour moi et votre code est:

1) Je ne vois pas où vous avez ajouté un observateur pour la notification Nspersistentstorediportubiquitouscontentchanges tel que dans le code:

let nc : NSNotificationCenter = NSNotificationCenter.defaultCenter();
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
nc.addObserver(self, selector: "dataUpdated:",
        name: NSPersistentStoreDidImportUbiquitousContentChangesNotification,
        object: self.managedObjectContext?.persistentStoreCoordinator)

2) dans mon code dans la fonction qui saisit la notification (dataUpdated dans ce cas), il réinitialise le contexte managé objext avec le code suivant avant de mettre à jour l'affichage pour afficher les nouvelles données:

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
if let managedObjectContext = appDelegate.managedObjectContext {
     managedObjectContext.reset()
}

Après en réinitialisant le contexte de l'objet géré, je récupère à nouveau l'entité en utilisant le code:

let fetchRequest = NSFetchRequest(entityName: "ClassNameHere")
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
let fetchResults = managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as! [ClassNameHere]
1
répondu Rich G 2015-09-03 00:34:01