目标C语言 文档不上传到iCloud时,使用For Loops - iOS



我试图将一个充满文档的本地文件夹上传到远程iCloud文件夹。我编写这个方法是为了循环遍历本地文件夹中的文件数组,检查它们是否已经存在,如果不存在,则将它们上传到iCloud。注意:这段代码是在后台线程而不是主线程上执行的。

//Get the array of files in the local documents directory
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *localDocuments = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
//Compare the arrays then upload documents not already existent in iCloud
for (int item = 0; item < [localDocuments count]; item++) {
    //If the file does not exist in iCloud, upload it
     if (![[iCloud previousQueryResults] containsObject:[localDocuments objectAtIndex:item]]) {
          NSLog(@"Uploading %@ to iCloud...", [localDocuments objectAtIndex:item]);
          //Move the file to iCloud
          NSURL *destinationURL = [[[NSFileManager defaultManager] URLForUbiquityContainerIdentifier:nil] URLByAppendingPathComponent:[NSString stringWithFormat:@"Documents/%@",[localDocuments objectAtIndex:item]]];
          NSError *error;
          NSURL *directoryURL = [[NSURL alloc] initWithString:[documentsDirectory stringByAppendingPathComponent:[localDocuments objectAtIndex:item]]];
          BOOL success = [[NSFileManager defaultManager] setUbiquitous:YES itemAtURL:directoryURL destinationURL:destinationURL error:&error];
          if (success == NO) {
              //Determine Error
              NSLog(@"%@",error);
          }
     } else {
          ...
     } }

当我运行这段代码时,For循环工作得很好-我使用NSLog语句来查找它正在上传的文件 -并且每个存储在本地的文件都应该开始上传,而不是已经在iCloud中。For循环完成后,我使用developer.icloud.com检查哪些文档现在在iCloud中。只有一个文件(我的应用程序一直在制作但从未使用过的sqlite文件)从许多存储在本地上传到iCloud。为什么使用for循环时只上传一个文件?

当我使用相同的代码上传单个文件(没有For循环)时,它们会完美地上传到iCloud。为什么For循环会阻碍文件的上传?这是否与For循环继续执行下一行代码而不等待最后一个进程/行完成执行有关?这是怎么回事?

EDIT:通常当我上传大文件到iCloud(不使用For Loop)时,我可以在iCloud开发网站上看到该文件几乎立即处于待上传状态。我在WiFi上测试一切,我已经等了一段时间,但什么也没有出现(除了sqlite文件)。

EDIT:我还检查了不同的方法中的iCloud可用性,如果iCloud可用,则允许调用此方法。我还仔细阅读了文档,并在苹果网站上观看了WWDC视频,但这些视频很复杂,对我想做的事情没有提供太多解释。

EDIT:修改了上面的代码(添加了错误功能)之后,我现在在日志中得到了这个错误消息:

Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" UserInfo=0x1f5dd070 {NSUnderlyingError=0x208ad9b0 "The operation couldn’t be completed. (LibrarianErrorDomain error 2 - No source URL specified.)"}

这使事情变得更加混乱,因为其中一个文件上传成功,而其他文件没有。

好的,最后的编辑是有用的。错误提示源URL(代码中的directoryURL)丢失——可能是因为它是nil。为什么是nil ?因为你造错了。您正在使用-[NSURL initWithString:],并且文档说:

该字符串必须符合RFC 2396中描述的URL格式。此方法根据rfc1738和1808解析URLString。

您正在传递文件路径,而不是URL。如果你传递给NSURL一些它不能识别为有效URL的东西,它通常返回nil。看起来NSURL无论如何都会频繁地生成一个文件URL,但失败是这里的预期行为。据我所知,如果文件名不包含空格,它似乎可以工作,但这没有记录,也不是你可以依赖的东西。

您应该做的是更改初始化directoryURL的行,使用接受文件路径的东西。比如:

NSURL *directoryURL = [NSURL fileURLWithPath:[documentsDirectory stringByAppendingPathComponent:[localDocuments objectAtIndex:item]]];

另外,确保验证directoryURL不是nil,以防万一。

最新更新