如何使用目标 C 在 iOS 上本地下载和保存文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5323427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I download and save a file locally on iOS using objective C?
提问by bogdan
I'm new to Objective-C and I want to download a file from the web (if it was changed on the webserver) and save it locally so it can be used by my application.
我是 Objective-C 的新手,我想从网络下载一个文件(如果它在网络服务器上被更改)并将其保存在本地,以便我的应用程序可以使用它。
Mainly I want to implement what wget --timestamp <url>
does.
主要是我想实现什么wget --timestamp <url>
。
回答by Henning
I'm not sure what wget is, but to get a file from the web and store it locally, you can use NSData:
我不确定 wget 是什么,但是要从 Web 获取文件并将其存储在本地,您可以使用 NSData:
NSString *stringURL = @"http://www.somewhere.com/thefile.png";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"filename.png"];
[urlData writeToFile:filePath atomically:YES];
}
回答by bandejapaisa
NSURLSession introduced in iOS 7, is the recommended SDK way of downloading a file. No need to import 3rd party libraries.
NSURLSession 在 iOS 7 中引入,是推荐的 SDK 下载文件方式。无需导入第 3 方库。
NSURL *url = [NSURL URLWithString:@"http://www.something.com/file"];
NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:url];
NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
self.downloadTask = [self.urlSession downloadTaskWithRequest:downloadRequest];
[self.downloadTask resume];
You can then use the NSURLSessionDownloadDelegate delegate methods to monitor errors, download completion, download progress etc... There are inline block completion handler callback methods too if you prefer. Apples docs explain when you need to use one over the other.
然后,您可以使用 NSURLSessionDownloadDelegate 委托方法来监视错误、下载完成、下载进度等……如果您愿意,也可以使用内联块完成处理程序回调方法。Apples 文档解释了何时需要使用一个而不是另一个。
Have a read of these articles:
阅读以下文章:
objc.io NSURLConnection to NSURLSession
objc.io NSURLConnection 到 NSURLSession
回答by Tibidabo
I would use an asynchronousaccess using a completion block.
我会使用完成块来使用异步访问。
This example saves the Google logo to the document directory of the device. (iOS 5+, OSX 10.7+)
本示例将 Google 徽标保存到设备的文档目录中。(iOS 5+, OSX 10.7+)
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentDir stringByAppendingPathComponent:@"GoogleLogo.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com/images/srpr/logo11w.png"]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(@"Download Error:%@",error.description);
}
if (data) {
[data writeToFile:filePath atomically:YES];
NSLog(@"File is saved to %@",filePath);
}
}];
回答by pixelfreak
I think a much easier way is to use ASIHTTPRequest. Three lines of code can accomplish this:
我认为更简单的方法是使用 ASIHTTPRequest。三行代码就可以做到这一点:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:@"/path/to/my_file.txt"];
[request startSynchronous];
UPDATE: I should mention that ASIHTTPRequest is no longer maintained. The author has specifically advised people to use other framework instead, like AFNetworking
更新:我应该提到 ASIHTTPRequest 不再维护。作者特别建议人们改用其他框架,例如AFNetworking
回答by Ali
Sometime ago I implemented an easy to use "download manager" library: PTDownloadManager. You could give it a shot!
前段时间我实现了一个易于使用的“下载管理器”库:PTDownloadManager。你可以试一试!