Why is UbiquityContainer nil if user not logged into iCloud?

97 Views Asked by At

I would like to use the UbiquityContainer in order to have an iCloud backup of the coredata. However if I am not logged into the iCloud on the simulator the ubContainer below remains nil.

-(void)addSqliteStoreToPersistentStoreCoordinator:(NSPersistentStoreCoordinator *)psc{
    NSError *error = nil;
    NSFileManager *fm = [NSFileManager defaultManager];
    NSURL *ubContainer = [fm URLForUbiquityContainerIdentifier:nil]; // Why nil???????
    NSURL *storeURL = [ubContainer URLByAppendingPathComponent:@"f11Remote.sqlite"];
    NSMutableDictionary *options = [NSMutableDictionary dictionary];
    [options setObject:[NSNumber numberWithBool:YES] forKey:NSMigratePersistentStoresAutomaticallyOption];
    [options setObject:[NSNumber numberWithBool:YES] forKey:NSInferMappingModelAutomaticallyOption];
    [options setObject:[NSDictionary dictionaryWithObjectsAndKeys:@"FULL", @"synchronous", nil] forKey:NSSQLitePragmasOption];
    [options setObject:@"f11iCloudStore" forKey:NSPersistentStoreUbiquitousContentNameKey];
    [options setValue:ubContainer forKey:NSPersistentStoreUbiquitousContentURLKey];
    sqliteStore = [psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:options error:&error];
    if (!sqliteStore)
        [NSException raise:@"FTDatastore: Couldn't open the local SQLite database." format:@"Reason: %@", [error localizedDescription]];
}

I was expecting an offline version of it to work in the meanwhile and behave like core data, until the user logs into the iCloud. What can be done?

1

There are 1 best solutions below

1
On

You need a fallback store in case the user did not activate iCloud.

NSURL *storeDirectory = [[NSFileManager defaultManager] 
                        URLForUbiquityContainerIdentifier:nil];

Why nil?

If you specify nil for this parameter, this method returns the first container listed in the com.apple.developer.ubiquity-container-identifiers entitlement array.

If the resulting URL is nil, iCloud is likely disabled. You have to provide an alternative URL.

if (!storeDirectory) {
   storeDirectory = [self applicationDocumentsDirectory]; // implement yourself
   NSLog(@"Falling back to local store.");
}