我创建了一个 UIDocument 来包装一个自定义对象。UIDocument 已成功保存到 iCloud,并且每次运行应用程序时都成功加载了每个 UIDocument。但是,当我尝试在新设备(iPhone 5)上运行该应用程序时,它不会从 iCloud 加载任何 UIDocument,但我可以在“设置”下检查 iCloud 并查看保存在我的应用程序下的文件。有没有人有一些步骤来检查为什么一个设备(iPhone 4)可以加载而另一个(iPhone 5)不能?我也无法从 iPhone 5 设备创建新的 UIDocument。
编辑
- (void)loadObjects
{
if (!self.objects)
{
self.objects = [[NSMutableArray alloc] init];
}
NSURL *baseURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (baseURL)
{
self.query = [[NSMetadataQuery alloc] init];
[self.query setSearchScopes:[NSArray arrayWithObject:NSMetadataQueryUbiquitousDocumentsScope]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K like 'Object_*'", NSMetadataItemFSNameKey];
[self.query setPredicate:predicate];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(queryDidFinish:) name:NSMetadataQueryDidFinishGatheringNotification object:self.query];
[nc addObserver:self selector:@selector(queryDidUpdate:) name:NSMetadataQueryDidUpdateNotification object:self.query];
[self.query startQuery];
}
}
- (void)queryDidFinish:(NSNotification *)notification
{
[self processQueryResults:notification.object];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidFinishGatheringNotification object:notification.object];
self.query = nil;
}
- (void)queryDidUpdate:(NSNotification *)notification
{
[self processQueryResults:notification.object];
[[NSNotificationCenter defaultCenter] removeObserver:self name:NSMetadataQueryDidFinishGatheringNotification object:notification.object];
self.query = nil;
}
- (void)processQueryResults:(NSMetadataQuery *)query
{
[query disableUpdates];
[query stopQuery];
[self.objects removeAllObjects];
[query.results enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSURL *documentURL = [(NSMetadataItem *)obj valueForAttribute:NSMetadataItemURLKey];
ObjectDocument *document = [[ObjectDocument alloc] initWithFileURL:documentURL];
[document openWithCompletionHandler:^(BOOL success) {
if (success) {
[self.objects addObject:document];
[self sortObjects];
[self.tableView reloadData];
}
}];
}];
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)save:(Object *)object
{
NSURL *baseURL = [[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil];
if (baseURL)
{
NSURL *documentsURL = [baseURL URLByAppendingPathComponent:@"Documents"];
NSURL *documentURL = [documentsURL URLByAppendingPathComponent:[NSString stringWithFormat:@"Object_%f", [object.date timeIntervalSince1970]]];
TVBFlightDocument *document = [[ObjectDocument alloc] initWithFileURL:documentURL];
document.object = object;
[document saveToURL:documentURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) {
NSLog(@"Save succeeded.");
[_objects addObject:document];
[self sortObjects];
} else {
NSLog(@"Save failed.");
}
}];
}
}
iPhone 5 上的应用程序不会加载存储在 iCloud 中的对象,但 iPhone 4 会从 iCloud 文档中加载对象。