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

I'm new to Objective-C and I want to download a file from the web (if it was changed on the webserver) and save it locally so it can be used by my application.

Mainly I want to implement what wget --timestamp <url> does.

This question is related to objective-c ios download wget local-storage

The answer is


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


There are so many ways:

  1. NSURL

  2. ASIHTTP

  3. libcurl

  4. easyget, a commercial one with powerful features.


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

I think a much easier way is to use ASIHTTPRequest. Three lines of code can accomplish this:

ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:@"/path/to/my_file.txt"];
[request startSynchronous];

Link to Reference

UPDATE: I should mention that ASIHTTPRequest is no longer maintained. The author has specifically advised people to use other framework instead, like AFNetworking


Sometime ago I implemented an easy to use "download manager" library: PTDownloadManager. You could give it a shot!


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

Examples related to objective-c

Adding a UISegmentedControl to UITableView Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Warp \ bend effect on a UIView? Use NSInteger as array index Detect if the device is iPhone X Linker Command failed with exit code 1 (use -v to see invocation), Xcode 8, Swift 3 ITSAppUsesNonExemptEncryption export compliance while internal testing? How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem? Change status bar text color to light in iOS 9 with Objective-C

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to download

how to download file in react js How do I download a file with Angular2 or greater Unknown URL content://downloads/my_downloads python save image from url How to download a file using a Java REST service and a data stream How to download file in swift? Where can I download Eclipse Android bundle? How to download image from url android download pdf from url then open it with a pdf reader Flask Download a File

Examples related to wget

How to `wget` a list of URLs in a text file? How to install wget in macOS? wget ssl alert handshake failure How to run wget inside Ubuntu Docker image? Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS How to use Python requests to fake a browser visit a.k.a and generate User Agent? wget/curl large file from google drive wget: unable to resolve host address `http' Python equivalent of a given wget command How to download HTTP directory with all files and sub-directories as they appear on the online files/folders list?

Examples related to local-storage

Angular 6: saving data to local storage Is it safe to store a JWT in localStorage with ReactJS? How to save to local storage using Flutter? Setting and getting localStorage with jQuery Local storage in Angular 2 How to store token in Local or Session Storage in Angular 2? QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota What is the difference between localStorage, sessionStorage, session and cookies? How to save an image to localStorage and display it on the next page? Can local storage ever be considered secure?