[英]Download and unpack a *.tgz file to a subdirectory of the Documents directory
[英]download file to Documents directory
我正在尝试将下载的文件复制到应用程序文档目录中的特定文件夹,但似乎无法正常运行。 我使用的代码是:
NSString *itemPathString = @"http://pathToFolder/folder/myFile.doc";
NSURL *myUrl = [NSURL URLWithString:itemPathString];
NSArray *paths = [fm URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
NSURL *folderPath = [[paths objectAtIndex:0] URLByAppendingPathComponent:@"folder"];
NSURL *itemURL = [documentsPath URLByAppendingPathComponent:@"myFile.doc"];
// copy to documents directory asynchronously
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSFileManager *theFM = [[NSFileManager alloc] init];
NSError *error;
[theFM copyItemAtURL:myUrl toURL:itemURL error:&error];
}
});
我可以检索该文件,但不能复制它。 谁能告诉我上面的代码有什么问题吗?
如果从服务器下载文件,如果文件很小(例如,以kb为单位,而不是以mb为单位),则可以使用dataWithContentsOfURL
。 您可以使用该方法将文件加载到内存中,然后使用NSData
实例方法writeToFile
保存文件。
但是,如果文件较大,则需要使用NSURLConnection
,它不会尝试将整个文件保存在内存中,而是在适当的时候将其写入文件系统。 但是,这里的技巧是,如果您要下载多个文件,则必须顺序下载它们,或者封装NSURLConnection
和NSOutputStream
,以便每次同时下载时都可以拥有单独的副本。
我上载了一个下载管理器项目,该项目演示了NSURLConnection
实现的外观,但这并不简单。 您可能希望考虑使用已建立的第三方库,例如ASIHTTPRequest或RestKit 。
如果要访问具有给定名称的文件夹,则应检查该文件夹是否存在以及是否创建。 这样可以很容易做到:
NSString *folder = [documentsPath stringByAppendingPathComponent:folderName];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
if (![fileManager fileExistsAtPath:folder]) {
[fileManager createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:&error];
}
if (error != nil) {
NSLog(@"Some error: %@", error);
return;
}
编辑
如果要检查是否在设备上正确创建了文件夹,请转到管理器->设备-> [YourDevelopingDeviceWhereTheAppWasInstalled]->应用程序-> [YourApplication]
在下部,您至少应该看到一些文件夹,例如“文档”。 如果成功,您创建的文件夹也是如此。
您需要在复制文件之前创建任何中间目录。 签入Simulator文件夹以查看是否在应用程序Documents-folder中创建了“ folder”目录。
模拟器的路径是/ Users / $ username / Library / Application Support / iPhone Simulator /
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.