How do I download and save a file locally on iOS using objective C? [duplicate] How do I download and save a file locally on iOS using objective C? [duplicate] ios ios

How do I download and save a file locally on iOS using objective C? [duplicate]


I'm not sure what wget is, but to get a file from the web and store it locally, you can use NSData:

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


NSURLSession introduced in iOS 7, is the recommended SDK way of downloading a file. No need to import 3rd party libraries.

NSURL *url = [NSURL URLWithString:@"http://www.something.com/file"];NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:url];NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];self.downloadTask = [self.urlSession downloadTaskWithRequest:downloadRequest];[self.downloadTask resume];

You can then use the NSURLSessionDownloadDelegate delegate methods to monitor errors, download completion, download progress etc... There are inline block completion handler callback methods too if you prefer. Apples docs explain when you need to use one over the other.

Have a read of these articles:

objc.io NSURLConnection to NSURLSession

URL Loading System Programming Guide


I would use an asynchronous access using a completion block.

This example saves the Google logo to the document directory of the device. (iOS 5+, OSX 10.7+)

NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];NSString *filePath = [documentDir stringByAppendingPathComponent:@"GoogleLogo.png"];NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com/images/srpr/logo11w.png"]];[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {    if (error) {        NSLog(@"Download Error:%@",error.description);    }    if (data) {        [data writeToFile:filePath atomically:YES];        NSLog(@"File is saved to %@",filePath);    }}];