Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move local Core Data to iCloud

How can I enable iCloud Core Data in an app which already uses local storage Core Data?

I've tried to use NSPersistentStoreUbiquitousContentNameKey in my persistent store options. Unfortunately, this option enables iCloud but does not transfer any of the local data to iCloud. I can't seem to get migratePersistentStore:toURL:options:withType:error: to work either. I provide the persistent store, its URL, iCloud options, etc. and it still will not migrate the existing local data to iCloud. Here's how I'm using the method:

- (void)migratePersistentStoreWithOptions:(NSDictionary *)options {
    NSError *error;
    self.storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite", self.SQLiteFileName]];

    NSPersistentStore *store = [self.persistentStoreCoordinator migratePersistentStore:self.persistentStoreCoordinator.persistentStores.firstObject toURL:self.storeURL options:options withType:NSSQLiteStoreType error:&error];
    if (store) NSLog(@"[CoreData Manager] Store was successfully migrated");
    else NSLog(@"[CoreData Manager] Error migrating persistent store: %@", error);
} 

The local storage remains separate from the iCloud storage. If possible, I'd like to move the local Core Data to iCloud without manually transferring each entity.

Any ideas? I can find lots of articles, tutorials, and posts about moving back to local storage from iCloud - but I want to move from local storage to iCloud.

like image 391
Sam Spencer Avatar asked Aug 13 '14 20:08

Sam Spencer


2 Answers

Here's what you'll need to do

  1. Create a local NSPersistentStoreCoordinator
  2. Add your existing persistent store to that coordinator and store a reference to this new returned store.
  3. Call that handy migratePersistStore:... providing the store from #2, a URL for the store in the documents directory with a different file name and the all important options including the NSPersistentStoreUbiquitousContentNameKey key.

Here's the code, notes in-line.

NSURL *documentsDirectory = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

//This is the path to the new store. Note it has a different file name
NSURL *storeURL = [documentsDirectory URLByAppendingPathComponent:@"TestRemote.sqlite"];

//This is the path to the existing store
NSURL *seedStoreURL = [documentsDirectory URLByAppendingPathComponent:@"Test.sqlite"];

//You should create a new store here instead of using the one you presumably already have access to
NSPersistentStoreCoordinator *coord = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:self.managedObjectModel];

NSError *seedStoreError;
NSDictionary *seedStoreOptions = @{ NSReadOnlyPersistentStoreOption: @YES };
NSPersistentStore *seedStore = [coord addPersistentStoreWithType:NSSQLiteStoreType
                                                   configuration:nil
                                                             URL:seedStoreURL
                                                         options:seedStoreOptions
                                                           error:&seedStoreError];

NSDictionary *iCloudOptions = @{ NSPersistentStoreUbiquitousContentNameKey: @"MyiCloudStore" };
NSOperationQueue *queue = [[NSOperationQueue alloc] init];

//This is using an operation queue because this happens synchronously
[queue addOperationWithBlock:^{
    NSError *blockError;
    [coord migratePersistentStore:seedStore
                            toURL:storeURL
                          options:iCloudOptions
                         withType:NSSQLiteStoreType
                            error:&blockError];

    NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
    [mainQueue addOperationWithBlock:^{
        // This will be called when the migration is done
    }];
}];

Note that after you do this migration, you'll need to configure the persistent store you use with your MOC with the new URL and always include the iCloudOptions above with the NSPersistentStoreUbiquitousContentNameKey key.

This was based on Apple's documentation.

After completion, you should see a new folder in your Documents folder in the simulator folder (~/Library/Application Support/iPhone Simulator/...) labeled CoreDataUbiquitySupport. Nested deep in there is your iCloud synced sqlite store.

Tada!


EDIT: Oh and make sure you have created an iCloud entitlement and included it in your bundle. You should be able to do that all within Xcode, but you can update it on the development portal too.

like image 141
Acey Avatar answered Sep 27 '22 20:09

Acey


Take a look at this sample app which includes code to migrate a local core data store to iCloud and back again. Best read the associated docs and build the sample apps in your environment to get them working and once they are working then try and refactor your code to use a similar approach.

Feel free to send me an email for further help. Apologies for not giving you an answer here but it can be quite a complicated issue to deal with.

http://ossh.com.au/design-and-technology/software-development/sample-library-style-ios-core-data-app-with-icloud-integration/

like image 20
Duncan Groenewald Avatar answered Sep 27 '22 20:09

Duncan Groenewald