NSMetadataQueryDidUpdateNotification可以与NSFileManager setUbiquitous一起使用

时间:2014-03-07 09:35:27

标签: icloud nsfilemanager

我正在尝试使用NSMetadataQueryDidUpdateNotification跟踪我的icloud上传进度..但它无法正常工作......我不知道问题是什么..

这是我上传到icloud的代码

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
    NSFileCoordinator* fileCoordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
    [fileCoordinator coordinateReadingItemAtURL:backupUrl options:NSFileCoordinatorReadingWithoutChanges error:nil byAccessor:^(NSURL *newURL) {
        NSFileManager*  fm = [NSFileManager defaultManager];
        NSError *theError = nil;

        BOOL success =[fm setUbiquitous:YES itemAtURL:backupUrl destinationURL:[[ubiq URLByAppendingPathComponent:@"Documents" isDirectory:true] URLByAppendingPathComponent:bName] error:&theError];

        if (!(success)) {
            [progView dismiss];
            UIAlertView* alertFail=[[UIAlertView alloc]initWithTitle:@"Backup Error" message:@"Could not backup to iCloud." delegate:Nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alertFail show];
            NSLog(@"iCloud error: %@", [theError localizedDescription]);
        }
        else{
            [self loadNotes:bName];
        }
    }];
});

以及用于跟踪上传进度的此代码

- (void)loadNotes:(NSString *)bname {
self.alertQuery = [[NSMetadataQuery alloc] init];
[self.alertQuery setPredicate:[NSPredicate predicateWithFormat:@"%K LIKE %@", NSMetadataItemFSNameKey, bname]];
[self.alertQuery setSearchScopes:@[NSMetadataQueryUbiquitousDataScope]];
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(liveupdate:) name:NSMetadataQueryDidUpdateNotification object:self.alertQuery];
[self.alertQuery startQuery];
}

-(void)liveupdate:(NSNotification *)note {
    NSMetadataQuery* query=[note object];
    if ([query resultCount]==0){
        return;
    }
    NSMetadataItem* item=[query resultAtIndex:0];
    float progress=[[item valueForAttribute:NSMetadataUbiquitousItemPercentUploadedKey]floatValue];

[progView.progBar setProgress:progress animated:NO];

if ([[item valueForAttribute:NSMetadataUbiquitousItemIsUploadedKey] boolValue]){
    [query stopQuery];
    [query disableUpdates];
    _alertQuery=nil;
    [progView dismiss];
}
}

代码有什么问题......

有人可以告诉我在NSFileManager setObiquitous中跟踪icloud上传进度的最佳方法是什么....

谢谢......

1 个答案:

答案 0 :(得分:1)

您可能希望观察首先触发的NSMetadataQueryDidFinishGatheringNotification通知,并使用初始结果集。

但即便如此,您可能无法获得所需内容,因为只有在结果集发生变化时才会触发更新通知。您正在搜索特定文件,由于该文件未被删除或类似,因此即使文件上传或下载,您的结果集也将保持不变。

根据我的经验,NSMetadataQuery对监控上传和下载进度不是很有效。你可以破解它几乎可以工作,但它绝不是你想要的。

您可以做的最好的事情是触发元数据查询,观察完成收集通知,停止查询,然后再次启动查询。每隔一秒左右定期执行此操作,您应该能够跟踪进度。

您还应该考虑是否确实要跟踪单个文件的进度。这取决于文件的大小。在许多情况下,您可能最好跟踪要上载/下载的文件数或剩余的总字节数。

如果是这种情况,您可以尝试设置包含包含上传/下载状态的谓词的元数据。当文件完成上传/下载时,这将不断触发通知。您可以找到此here的示例。寻找方法startMonitoringMetadata