如何从互联网下载文件并保存在iPhone上的“文档”中?
问题描述:
我的远程服务器上有一个文件夹,里面有几个.png文件。我想从我的应用程序中下载这些内容并将它们存储在应用程序的“文档”文件夹中。我怎样才能做到这一点?如何从互联网下载文件并保存在iPhone上的“文档”中?
答
简单的方法是使用NSData的便捷方法initWithContentOfURL:
和writeToFile:atomically:
分别获取数据和写出数据。请记住,这是同步的,并会阻止您执行它的任何线程,直到抓取和写入完成。
例如:
// Create and escape the URL for the fetch
NSString *URLString = @"http://example.com/example.png";
NSURL *URL = [NSURL URLWithString:
[URLString stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding]];
// Do the fetch - blocks!
NSData *imageData = [NSData dataWithContentsOfURL:URL];
if(imageData == nil) {
// Error - handle appropriately
}
// Do the write
NSString *filePath = [[self documentsDirectory]
stringByAppendingPathComponent:@"image.png"];
[imageData writeToFile:filePath atomically:YES];
凡documentsDirectory
方法是无耻地从this question被盗:
- (NSString *)documentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
return [paths objectAtIndex:0];
}
但是,除非你打算线程它自己这个会停止,而文件的下载用户界面活动。你可以改为查看NSURLConnection及其委托 - 它在后台下载并通知委托有关异步下载的数据,所以你可以建立一个NSMutableData实例,然后在连接完成时写出它。你代表可能包含如下方法:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the data to some preexisting @property NSMutableData *dataAccumulator;
[self.dataAccumulator appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Do the write
NSString *filePath = [[self documentsDirectory]
stringByAppendingPathComponent:@"image.png"];
[imageData writeToFile:filePath atomically:YES];
}
的小细节,像声明dataAccumulator
和处理错误,都留给读者:)
的重要文件:
谢谢!嗯...同步?这是否意味着我在工作完成时最好使用“进度轮/酒吧”? – RexOnRoids 2009-08-26 03:09:58
同步意味着程序中的所有活动(以及主线程)将完全停止,直到下载完成。这意味着用户界面将显示为冻结状态,并且直到下载完成后,旋转器才会启动动画制作(使其非常无用)。第二种方法是异步下载,让您的程序在后台下载时在前台继续工作。无论哪种方式,是的,你应该使用某种进度指示器。 – Tim 2009-08-26 03:13:06