How to display an AlertView requesting permission to seed iCloud once and only once in app's iCloud lifetime?

244 Views Asked by At

I have one question near the end.

I am working from the belief/experience that seeding iCloud more than once is a bad idea and that if a user can do the wrong thing, he probably will sooner or later.

What I want to do:

A. When the user changes the app preference "Enable iCloud" from NO to YES, display AlertView asking (Yes or No) if the user wishes to seed the cloud with existing non-iCloud Data.

B. Ensure that the app seeds iCloud only once on an iCloud account, refraining to put up the AlertView once seeding is completed the first time.

My Method:

  1. Following Apple's Docs concerning the proper use of NSUbiquitousKeyValueStore, I am using the following method in, - (void)application: dFLWOptions:

    - (void)updateKVStoreItems:(NSNotification*)notification {
        // Get the list of keys that changed.
        NSDictionary* userInfo = [notification userInfo];
        NSNumber* reasonForChange = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangeReasonKey];
        NSInteger reason = -1;
            // If a reason could not be determined, do not update anything.
        if (!reasonForChange)
            return;
            // Update only for changes from the server.
        reason = [reasonForChange integerValue];
        if ((reason == NSUbiquitousKeyValueStoreServerChange) ||
             (reason == NSUbiquitousKeyValueStoreInitialSyncChange)) { // 0 || 1
                // If something is changing externally, get the changes
                // and update the corresponding keys locally.
            NSArray* changedKeys = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangedKeysKey];
            NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore];
            NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
                // This loop assumes you are using the same key names in both
                // the user defaults database and the iCloud key-value store
            for (NSString* key in changedKeys) {//Only one key: @"iCloudSeeded" a BOOL
                BOOL bValue = [store boolForKey:key];
                id value = [store objectForKey:@"iCloudSeeded"];
                [userDefaults setObject:value forKey:key];
            }
        }
    

    }

  2. Include the following code near the top of application: dFLWO:

    NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                    selector:@selector(updateKVStoreItems:)
                                            name:NSUbiquitousKeyValueStoreDidChangeExternallyNotification
                                                                 object:store]; // add appDelegate as observer
    
  3. After loading iCloud Store, then seed it with non-iCloud data ONLY if seeding has never been done

    - (BOOL)loadiCloudStore {
        if (_iCloudStore) {return YES;} // Don’t load iCloud store if it’s already loaded
    
        NSDictionary *options =
        @{
        NSMigratePersistentStoresAutomaticallyOption:@YES
        ,NSInferMappingModelAutomaticallyOption:@YES
        ,NSPersistentStoreUbiquitousContentNameKey:@"MainStore"
        };
        NSError *error=nil;
        _iCloudStore = [_coordinator addPersistentStoreWithType:NSSQLiteStoreType
                                configuration:nil URL:[self iCloudStoreURL] options:options error:&error];
        if (_iCloudStore) {
            NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore];
            BOOL iCloudSeeded =
                [store boolForKey:@"iCloudSeeded"];//If the key was not found, this method returns NO.
            if(!iCloudSeeded) // CONTROL IS HERE
                [self confirmMergeWithiCloud]; // Accept one USER confirmation for seeding in AlertView ONCE world wide
            return YES; // iCloud store loaded.
        }
        NSLog(@"** FAILED to configure the iCloud Store : %@ **", error);
        return NO;
    }
    
  4. Once the seeding is completed do the following to prevent any repeat seeding:

    if (alertView == self.seedAlertView) {
            if (buttonIndex == alertView.firstOtherButtonIndex) {
                [self seediCloud];
                NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore];
                [store setBool:YES  forKey:@"iCloudSeeded"]; // NEVER AGAIN 
                    //[store synchronize];
            }
        }
    }
    
  5. Be sure to get a total iCloud reset before the above process using:

    [NSPersistentStoreCoordinator
          removeUbiquitousContentAndPersistentStoreAtURL:[_iCloudStore URL]
          options:options
          error:&error])
    

    This is a very tidy solution to my problem, IMHO, but I can not quite get it done.

    MY QUESTION:

    How do I respond to the first notification to updateKVStoreItems: above? It is a notification with bad info. I says the value is TRUE, but I have never set it to TRUE. How do I set default values for a key in NSUbiquitousKeyValueStore?

    I find that the first notification is of reason : NSUbiquitousKeyValueStoreInitialSyncChange When that note comes in, bValue is YES. THIS IS MY PROBLEM. It is as if, iCloud/iOS assumes any new BOOL to be TRUE. I need this value to be NO initially so that I can go ahead and follow the Apple Docs and set the NSUserDefault to NO. And then Later when the seeding is done, to finally set the value: YES for the key:@"iCloudSeeded"

    I find I can not penetrate the meaning of the following from Apple:

    NSUbiquitousKeyValueStoreInitialSyncChange
    Your attempt to write to key-value storage was discarded because an initial download from iCloud has not yet happened. 
    That is, before you can first write key-value data, the system must ensure that your app’s local, on-disk cache matches the truth in iCloud.
    Initial downloads happen the first time a device is connected to an iCloud account, and when a user switches their primary iCloud account.
    

    I don't quite understand the implications of number 2 below, which I found online:

     NSUbiquitousKeyValueStoreInitialSyncChange – slightly more complicated, only happens under these circumstances:
    1. You start the app and call synchronize
    2. Before iOS has chance to pull down the latest values from iCloud you make some changes.
    3. iOS gets the changes from iCloud.
    

    If this problem was with NSUserDefaults and not NSUbiquitousKeyValueStore, I believe I would need to go to registerDefaults.

    I am almost there, How do I do this please! Thanks for reading, Mark

1

There are 1 best solutions below

0
On BEST ANSWER

The code was looking for both

    A. NSUbiquitousKeyValueStoreInitialSyncChange and 
    B. NSUbiquitousKeyValueStoreServerChange

I was unable to figure out what to do with the notifications. I know see that I did not need to do anything with either. My app only needs to read and write, in order to solve the problem I laid out in my question header.

The app gets the current value with:

    NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore];
    BOOL iCloudSeeded = [store boolForKey:@"iCloudSeeded"];

The app sets the value in the NSUbiquitousKeyValueStore with:

    NSUbiquitousKeyValueStore* store = [NSUbiquitousKeyValueStore defaultStore];
    [store setBool:YES  forKey:@"iCloudSeeded"];

I believe I am correct in saying the following: Writing is done into memory. Very soon thereafter the data is put by the system onto disk. From there it is taken and put into iCloud and is made available to the other devices running the same app on the same iCloud account. In the application I have described, no observer needs to be added, and nothing else needs to be done. This is maybe an "unusual" use of NSUbiquitousKeyValueStore.

If you came here looking for a an more "usual" use, say when a user type something into a textview and it later appears on a view of other devices running the same app, check out a simple demo I came across at :

    https://github.com/cgreening/CMGCloudSyncTest

The better functioning (monitoring only) notification handler follows:

    - (void)updateKVStoreItems:(NSNotification*)notification {
        NSNumber *reason = notification.userInfo[NSUbiquitousKeyValueStoreChangeReasonKey];
        if(!reason) return;
            // get the reason code
        NSInteger reasonCode = [notification.userInfo[NSUbiquitousKeyValueStoreChangeReasonKey] intValue];
        BOOL bValue;
        NSUbiquitousKeyValueStore *store;

        switch(reasonCode) {
            case NSUbiquitousKeyValueStoreServerChange:{ // code 0, monitoring only
                store = [NSUbiquitousKeyValueStore defaultStore];
                bValue = [store boolForKey:@"iCloudSeeded"];
                id value = [store objectForKey:@"iCloudSeeded"];
                DLog(@"New value for iCloudSeeded=%d\nNo Action need be take.",bValue);
                    // For monitoring set in UserDefaults
                [[NSUserDefaults standardUserDefaults] setObject:value forKey:@"iCloudSeeded"];
                break;
            }
            case NSUbiquitousKeyValueStoreAccountChange: {// ignore, log
                NSLog(@"NSUbiquitousKeyValueStoreAccountChange");
                break;
            }
            case NSUbiquitousKeyValueStoreInitialSyncChange:{ // ignore, log
                NSLog(@"NSUbiquitousKeyValueStoreInitialSyncChange");
                break;
            }
            case NSUbiquitousKeyValueStoreQuotaViolationChange:{ // ignore, log
                NSLog(@"Run out of space!");
                break;
            }
        }
    }

Adding 9/3/14 So sorry but I continued to have trouble using a BOOL, I switched to an NSString and now all is well.

METHOD TO ENSURE THAT THE "MERGE" BUTTON FOR SEEDING ICOUD IS USED AT MOST ONCE DURING APP LIFETIME

  1. Use NSString and not BOOL in KV_STORE. No need to add observer, except for learning

  2. In Constants.h :

    #define SEEDED_ICLOUD_MSG @"Have Seeded iCloud"
    #define ICLOUD_SEEDED_KEY @"iCloudSeeded"
    
  3. Before calling function to seed iCloud with non-iCloud data:

    NSUbiquitousKeyValueStore* kvStore = [NSUbiquitousKeyValueStore defaultStore];
    NSString* strMergeDataWithiCloudDone =
                [kvStore stringForKey:ICLOUD_SEEDED_KEY];
    NSComparisonResult *result = [strMergeDataWithiCloudDone compare:SEEDED_ICLOUD_MSG];
    if(result != NSOrderedSame)
        //put up UIAlert asking user if seeding is desired.
    
  4. If user chooses YES : set Value for Key after the merge is done.

    - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
        if (alertView == self.seedAlertView) {
            if (buttonIndex == alertView.firstOtherButtonIndex) {
                [self seediCloudwithNoniCloudData];
                NSUbiquitousKeyValueStore* kvStoretore = [NSUbiquitousKeyValueStore defaultStore];
                [store setObject:SEEDED_ICLOUD_MSG forKey:ICLOUD_SEEDED_KEY];
            }
        }
    }
    
  5. Thereafter on all devices, for all time, the code

    NSUbiquitousKeyValueStore* kvStoretore = [NSUbiquitousKeyValueStore defaultStore]; NSString* msg = [kvStore stringForKey:ICLOUD_SEEDED_KEY];

produces: msg == SEEDED_ICLOUD_MESSAGE