首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >iCloud: NSUbiquitousKeyValueStore问题

iCloud: NSUbiquitousKeyValueStore问题
EN

Stack Overflow用户
提问于 2014-03-01 16:54:42
回答 1查看 2.7K关注 0票数 0

我让我的应用程序中的iCloud能够保存一些首选项。在“功能”部分中启用了iCloud,并更新了我的配置文件:

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

代码语言:javascript
复制
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)。当我删除设备中的应用程序时,保存的数据是不可恢复的。显然,在其他设备中,数据也无法恢复。

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

数据似乎不是保存在iCloud上,只保存在本地。

在我的项目中,唯一“奇怪”的是项目名称与包名不一样。

更新:

我的问题只出现在iOs6上。在iOs7中,所有的功能都很好。当我在“调试导航器”中使用iOs 6的设备调试我的应用程序时,iCloud部分显示:

配置iCloud的所有步骤似乎都正常(对于使用iOs7的设备来说很好),如果我用下面的代码测试它,就可以了:

代码语言:javascript
复制
NSURL *ubiq = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (ubiq) {
    NSLog(@"iCloud at %@", ubiq);

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

怎么了?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-02 08:51:36

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

代码语言:javascript
复制
- (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);
    }
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22117306

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档