如何从url下载文件并存储在文档文件夹中 [英] how to download files from url and store in document folder

查看:113
本文介绍了如何从url下载文件并存储在文档文件夹中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个具有两个页面的应用程序(第一页显示数据列表,第二页显示详细数据)。

I created one application that has two page (first page for show list of data and second page for show detail data).

当单击任何单元格时下一页和下一页存在一个名称为:DOWNLOAD
的按钮,当我点击该按钮此文件下载并保存在文档文件夹中时。
我不知道。请指导我如何下载任何文件并存储在文件夹中。
我在互联网上搜索,但我不了解它。

when click on any cell go to next page and in next page exists one button with name : DOWNLOAD that I want when I click on that button this file download and save in document folder. I dont know about it. please guide me that how download any file and store in document folder. I searching in internet but I dont understand about it.

请告诉我如何使用一个按钮下载任何文件的代码。对不起,如果我不是很好的英语

please tell me with code that how downloaded any file with one button. Im sorry if I not good english.

推荐答案

这是我简单的朋友,

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

建议在单独的线程中执行代码。 em>

it advisable to execute the code in a separate thread.

编辑1:更多信息

1)对于大文件下载,

1) for large file downloads,

-(IBAction) downloadButtonPressed:(id)sender;{
    //download the file in a seperate thread.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSLog(@"Downloading Started");
        NSString *urlToDownload = @"http://www.somewhere.com/thefile.png";
        NSURL  *url = [NSURL URLWithString:urlToDownload];
        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"];

            //saving is done on main thread
            dispatch_async(dispatch_get_main_queue(), ^{
                [urlData writeToFile:filePath atomically:YES];
                NSLog(@"File Saved !");
            });
        }

    });

}

这篇关于如何从url下载文件并存储在文档文件夹中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆