【问题标题】:How to download files from internet and save in 'Documents' on iPhone?如何从 Internet 下载文件并保存在 iPhone 上的“文档”中?
【发布时间】:2009-08-26 02:56:56
【问题描述】:

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

【问题讨论】:

    标签: iphone uikit download directory


    【解决方案1】:

    简单的方法是使用 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 和处理错误之类的小细节留给读者 :)

    重要文件:

    【讨论】:

    • 谢谢!嗯……同步?这是否意味着我最好在工作完成时使用“进度轮/进度条”?
    • 同步意味着程序中的所有活动(嗯,主线程)将完全停止,直到下载完成。这意味着 UI 将在用户看来冻结,并且微调器在下载完成之前甚至不会开始动画(使它们变得非常无用)。第二种方法,异步下载,让您的程序在后台下载时继续在前台工作。无论哪种方式,是的,您应该使用某种进度指示器。
    猜你喜欢
    • 2012-08-03
    • 2011-01-07
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 2022-01-14
    相关资源
    最近更新 更多