iOS: Migrating existing Core Data-database into iCloud

I’m using Core Data in an existing application. Now I want to integrate iCloud so that the user can synchronize their contents between their iOS-devices. To do that I’ve written the following code for my NSPersistentStoreCoordinator (of course the placeholders are filled out in my code):

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {

if (persistentStoreCoordinator_ != nil) {
    return persistentStoreCoordinator_;
}

NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"<DB_Name>.sqlite"];

persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

NSPersistentStoreCoordinator* psc = persistentStoreCoordinator_;

if (IOS_VERSION_GREATER_THAN_OR_EQUAL_TO(@"5.0")) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSFileManager *fileManager = [NSFileManager defaultManager];

        // Migrate datamodel
        NSDictionary *options = nil;

        // this needs to match the entitlements and provisioning profile
        NSURL *cloudURL = [fileManager URLForUbiquityContainerIdentifier:@"<App_Identifier>"];
        NSString* coreDataCloudContent = [[cloudURL path] stringByAppendingPathComponent:@"data"];
        if ([coreDataCloudContent length] != 0) {
            // iCloud is available
            cloudURL = [NSURL fileURLWithPath:coreDataCloudContent];

            options = [NSDictionary dictionaryWithObjectsAndKeys:
                       [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                       [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
                       @"<App_Name>.store", NSPersistentStoreUbiquitousContentNameKey,
                       cloudURL, NSPersistentStoreUbiquitousContentURLKey,
                       nil];
        } else {
            // iCloud is not available
            options = [NSDictionary dictionaryWithObjectsAndKeys:
                       [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                       [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
                       nil];
        }

        NSError *error = nil;
        [psc lock];
        if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
        {
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        }
        [psc unlock];

        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"asynchronously added persistent store!");
            [[NSNotificationCenter defaultCenter] postNotificationName:@"RefetchAllDatabaseData" object:self userInfo:nil];
        });

    });

} else {
    NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                             [NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
                             [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
                             nil];

    NSError *error = nil;
    if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error])
    {
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    }
}

return persistentStoreCoordinator_;
}

With that code all new added data records are synchronized automatically between all iOS-devices, so that works exactly the way it should!

  • How to define CoreData relationship in Swift?
  • Core data, how to get NSManagedObject's ObjectId when NSFetchRequest returns NSDictionaryResultType?
  • What is the most efficient way to sync Core Data with JSON API
  • Prevent app from backing up documents folder?
  • How to assign CoreData many-to-many relationship in Swift?
  • NSPredicate With FUNCTION Not Working
  • But what I want is that also all the existing data records are synced between all devices; that doesn’t work yet. The existing records are still available within the app and can be used, but they are not synchronized.

    What do I need to do to get all the existing data records synced with iCloud too? I’ve experimented a bit with the method

    migratePersistentStore:toURL:options:withType:error:
    

    but without any success.

    I’m very grateful for any help!

    2 Solutions Collect From Internet About “iOS: Migrating existing Core Data-database into iCloud”

    Look up the WWDC 2012 session Using CoreData with iCloud. They discuss this during the final section, under the topic of seeding. They also have some sample code that you can get from the site that has an example. In short, you will have to open 2 persistent stores, set a fetch size, then grab batches from the source, loop through them and add them to the new store, and at batch size intervals, save and reset. Pretty simple.

    Check out WWDC 2012 – Using core data with iCloud. This technique is called seeding.
    Find the sample code at https://github.com/jab5990/TestCDiCloud/tree/master/Shared