0

我在我的应用程序中启用 iCloud 以保存一些首选项。iCloud 在功能部分启用,我的配置文件已更新:

在此处输入图像描述

我保存和检索测试示例的代码如下:

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);
}

我的问题是数据只保存在本地(如 NSUserDefaults)。当我删除设备中的应用程序时,保存的数据不可恢复。显然,在其他设备中,数据也无法恢复。

第一次保存数据。接下来,如果我再次打开应用程序,else 代码可以很好地检索数据。但是当我删除de app并再次运行时,数据没有保存。

似乎数据没有保存在 iCloud 上,只保存在本地。

我的项目中只有“奇怪”的是项目名称与包名称不同。

更新:

我的问题仅在 iOS6 中。在 iOs7 中一切正常。当我在带有 iOs 6 的设备中调试我的应用程序时,“调试导航器”iCloud 部分显示:

在此处输入图像描述

配置 iCloud 的所有步骤似乎都可以(对于具有 iOs7 的设备可以正常工作),如果我使用以下代码对其进行测试,则可以正常工作:

NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (ubiq) {
    NSLog(@"iCloud at %@", ubiq);

} else {
    NSLog(@"No iCloud access");
}

怎么了?

谢谢!

4

1 回答 1

5

您正在尝试从 iCloud 中检索尚未下载的数据。下载操作需要一些时间,您应该注册NSUbiquitousKeyValueStoreDidChangeExternallyNotification以便能够从 iCloud 访问新数据。这是一个示例代码:

- (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);
    }
}
于 2014-03-02T08:51:36.307 回答