18

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.

jacky
  • 181
  • 1
  • 2
  • 11

1 Answers1

50

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

    });

}
Thilina Chamath Hewagama
  • 9,039
  • 3
  • 32
  • 45