Sam*_*cer 6 for-loop objective-c ios icloud
我正在尝试将装满文档的本地文件夹上传到远程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 {
...
} }
Run Code Online (Sandbox Code Playgroud)
当我运行此代码时,For循环工作正常 - 我使用NSLog语句找出它正在上传的文件 - 并且本地存储的每个尚未存在于iCloud中的文件应该开始上传.For循环结束后,我使用developer.icloud.com检查iCloud中现在有哪些文档.在许多存储的本地上传到iCloud中只有一个文件(我的应用程序一直在制作但从不使用的sqlite文件).为什么在使用for循环时只上传一个文件?
当我使用相同的代码上传单个文件(没有For循环)时,他们会完美地上传到iCloud.为什么For循环阻碍了文件的上传?这是否与For循环有关,继续下一行代码而不等待最后一个进程/行完成执行?这里发生了什么?
编辑:通常当我将大文件上传到iCloud(不使用For循环)时,我可以在iCloud开发站点上看到该文件几乎立即被挂起.我正在通过WiFi测试一切,我已经等了一段时间但没有出现(除了sqlite文件).
编辑:我还检查了不同方法的iCloud可用性,然后允许在iCloud可用时调用此方法.我还确保阅读文档并在Apple的网站上观看WWDC视频,但它们很复杂,并没有为我正在尝试做的事情提供太多解释.
编辑:修改上面的代码(添加错误功能)后,我现在在日志中收到此错误消息:
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.)"}
Run Code Online (Sandbox Code Playgroud)
这使得事情变得更加混乱,因为其中一个文件成功上传,而其他文件则没有.
好的,最后一次编辑很有用.错误抱怨源URL(directoryURL在您的代码中)丢失 - 可能是因为它nil.为什么会这样nil?因为你错了.你正在使用-[NSURL initWithString:],而且文档说:
此字符串必须符合RFC 2396中所述的URL格式.此方法根据RFC 1738和1808解析URLString.
您传入的是文件路径,而不是URL.如果您传递的NSURL内容无法识别为有效的URL,则通常会返回nil.看起来好像NSURL经常会产生文件URL,但失败是这里的预期行为.从我所知道的,如果文件名不包含空格似乎可行,但是没有记录,也没有你可以依赖的东西.
您应该做的是更改初始化的行directoryURL以使用接受文件路径的内容.就像是:
NSURL *directoryURL = [NSURL fileURLWithPath:[documentsDirectory stringByAppendingPathComponent:[localDocuments objectAtIndex:item]]];
Run Code Online (Sandbox Code Playgroud)
另外,为了以防万一,请确保验证directoryURL不是nil.
| 归档时间: |
|
| 查看次数: |
1192 次 |
| 最近记录: |