I'm enabling iCloud in my app to save some preferences. iCloud is enabled in capabilities section and my provisioning profile is updated:
My code to save and retrieve the test example is as follows:
NSUbiquitousKeyValueStore *cloudStore = [NSUbiquitousKeyValueStore defaultStore];
if ([[cloudStore stringForKey:@"testString"] length] == 0) {
NSLog(@"Nothing in iCloud - setting a value...");
[cloudStore setString:@"I'm live in iCloud!" forKey:@"testString"];
[cloudStore synchronize];
} else {
NSString *result = [cloudStore stringForKey:@"testString"];
NSLog(@"Found something in iCloud - here it is: %@", result);
}
My problem is that the data only is saved locally (like NSUserDefaults). When I delete the app in a device the saved data is not recoverable. In other device, obviously, the data can't recover either.
The first time the data is saved. Next if I open another time the app the else code retrieve the data fine. But when I delete de app and run again, the data is no saved.
Seems the data is not saved on iCloud, only locally.
Only "strange" in my project is that the project name isn't the same as the bundle name.
UPDATE:
My issue is only in iOs6. In iOs7 all works fine. When I debug my app in a device with iOs 6 in "debug navigator" iCloud section shows:
All steps to configure iCloud seems ok (for a device with iOs7 works fine) and if I test it with the following code works ok:
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (ubiq) {
NSLog(@"iCloud at %@", ubiq);
} else {
NSLog(@"No iCloud access");
}
What's wrong?
Thanks!
You are attempting to retrieve data from iCloud when it is not downloaded yet. The downloading operation takes some time and you should register for NSUbiquitousKeyValueStoreDidChangeExternallyNotification to be able to access fresh data from iCloud. Here is a sample code:
- (void) registerForiCloudNotificatons
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleChangesFromiCloud:)
name:NSUbiquitousKeyValueStoreDidChangeExternallyNotification
object:[NSUbiquitousKeyValueStore defaultStore]];
}
- (void) handleChangesFromiCloud: (NSNotification *) notification
{
NSDictionary * userInfo = [notification userInfo];
NSInteger reason = [[userInfo objectForKey:NSUbiquitousKeyValueStoreChangeReasonKey] integerValue];
// 4 reasons:
switch (reason) {
case NSUbiquitousKeyValueStoreServerChange:
// Updated values
break;
case NSUbiquitousKeyValueStoreInitialSyncChange:
// First launch
break;
case NSUbiquitousKeyValueStoreQuotaViolationChange:
// No free space
break;
case NSUbiquitousKeyValueStoreAccountChange:
// iCloud accound changed
break;
default:
break;
}
NSArray * keys = [userInfo objectForKey:NSUbiquitousKeyValueStoreChangedKeysKey];
for (NSString * key in keys)
{
NSLog(@"Value for key %@ changed", key);
}
}