如何从互联网下载文件并保存在“文档”中在 iPhone 上?

发布于 2024-08-03 09:00:06 字数 77 浏览 2 评论 0原文

我的远程服务器上有一个文件夹,其中有一些 .png 文件。我想从我的应用程序中下载这些并将它们存储在应用程序的“文档”文件夹中。我该怎么做?

I have a folder on my remote server that has a few .png files in it. I want to download these from within my app and store them in the apps 'Documents' folder. How can I do this?

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

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

发布评论

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

评论(1

梦醒灬来后我 2024-08-10 09:00:06

最简单的方法是使用 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 方法被无耻地从 这个问题

- (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 和处理错误,留给读者:)

重要文档:

The easy way is to use NSData's convenience methods initWithContentOfURL: and writeToFile:atomically: to get the data and write it out, respectively. Keep in mind this is synchronous and will block whatever thread you execute it on until the fetch and write are complete.

For example:

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

Where the documentsDirectory method is stolen shamelessly from this question:

- (NSString *)documentsDirectory {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}

However, unless you intend to thread it yourself this will stop UI activity while the file downloads. You may instead want to look into NSURLConnection and its delegate - it downloads in the background and notifies a delegate about data downloaded asynchronously, so you can build up an instance of NSMutableData then just write it out when the connection's done. Your delegate might contain methods like:

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

The little details, like declaring the dataAccumulator and handling errors, are left to the reader :)

The important documents:

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