ios 如何从url下载文件并存储在文档文件夹中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16392420/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 23:28:02  来源:igfitidea点击:

how to download files from url and store in document folder

iosobjective-cdownload

提问by Hymany

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

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

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.

请用代码告诉我如何一键下载任何文件。如果我英语不好,我很抱歉。

回答by Thilina Chamin Hewagama

It is this simple my friend,

我的朋友就是这么简单,

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

it advisable to execute the code in a separate thread.

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

EDIT 1: more info

编辑 1:更多信息

1) for large file downloads,

1)对于大文件下载,

-(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 !");
            });
        }

    });

}