【发布时间】:2009-08-26 02:56:56
【问题描述】:
我的远程服务器上有一个文件夹,里面有一些 .png 文件。我想从我的应用程序中下载这些并将它们存储在应用程序的“文档”文件夹中。我该怎么做?
【问题讨论】:
标签: iphone uikit download directory
我的远程服务器上有一个文件夹,里面有一些 .png 文件。我想从我的应用程序中下载这些并将它们存储在应用程序的“文档”文件夹中。我该怎么做?
【问题讨论】:
标签: iphone uikit download directory
简单的方法是使用 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];
}
但是,除非您打算自己线程化,否则这将在文件下载时停止 UI 活动。相反,您可能想查看 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 和处理错误之类的小细节留给读者 :)
重要文件:
【讨论】: