如何使用 Objective C 在 iOS 上本地下载并保存文件?

发布于 2024-10-21 23:11:46 字数 139 浏览 10 评论 0原文

我是 Objective-C 的新手,我想从网络下载一个文件(如果它在网络服务器上更改)并将其保存在本地,以便我的应用程序可以使用它。

主要是我想实现 wget --timestamp 所做的事情。

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.

Mainly I want to implement what wget --timestamp <url> does.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

巷子口的你 2024-10-28 23:11:46

我不确定 wget 是什么,但是要从网络获取文件并将其存储在本地,您可以使用 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];
}

I'm not sure what wget is, but to get a file from the web and store it locally, you can use 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];
}
决绝 2024-10-28 23:11:46

iOS 7 中引入的 NSURLSession 是推荐的 SDK 下载文件方式。无需导入第三方库。

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];

然后,您可以使用 NSURLSessionDownloadDelegate 委托方法来监视错误、下载完成、下载进度等...如果您愿意,也可以使用内联块完成处理程序回调方法。苹果文档解释了何时需要使用其中一种而不是另一种。

阅读以下文章:

objc.io NSURLConnection 到 NSURLSession< /a>

URL加载系统编程指南

NSURLSession introduced in iOS 7, is the recommended SDK way of downloading a file. No need to import 3rd party libraries.

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.

Have a read of these articles:

objc.io NSURLConnection to NSURLSession

URL Loading System Programming Guide

对你的占有欲 2024-10-28 23:11:46

我将使用使用完成块的异步访问。

本示例将 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);
    }
}];

I would use an asynchronous access using a completion block.

This example saves the Google logo to the document directory of the device. (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);
    }
}];
三生殊途 2024-10-28 23:11:46

我认为更简单的方法是使用 ASIHTTPRequest。三行代码即可完成此操作:

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:@"/path/to/my_file.txt"];
[request startSynchronous];

参考链接

更新:我应该提到 ASIHTTPRequest 不再维护。作者特别建议人们使用其他框架,例如 AFNetworking

I think a much easier way is to use ASIHTTPRequest. Three lines of code can accomplish this:

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:@"/path/to/my_file.txt"];
[request startSynchronous];

Link to Reference

UPDATE: I should mention that ASIHTTPRequest is no longer maintained. The author has specifically advised people to use other framework instead, like AFNetworking

同尘 2024-10-28 23:11:46

不久前,我实现了一个易于使用的“下载管理器”库:PTDownloadManager。你可以尝试一下!

Sometime ago I implemented an easy to use "download manager" library: PTDownloadManager. You could give it a shot!

最偏执的依靠 2024-10-28 23:11:46

有很多方法:

  1. NSURL

  2. ASIHTTP

  3. libcurl

  4. easyget,一款功能强大的商业应用。

There are so many ways:

  1. NSURL

  2. ASIHTTP

  3. libcurl

  4. easyget, a commercial one with powerful features.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文