How to download a file and save it to your app’s Documents directory

- by

Say you had the URL to a file on the web and you’d like to save said file in the app’s Documents directory. I thought it would be as simple as using the NSFilemanager and copying the URL. But it’s a little more complex than that.

Instead, we can use NSData to retrieve the data and use its method writeToFile to writeToURL. To download the file and turn it into NSData we need an NSURLRequest. We also need a URL to download from, and the location of the user’s Documents directory.

Let’s see how this works:

// the URL to save
NSURL *yourURL = [NSURL URLWithString:@""];
// turn it into a request and use NSData to load its content
NSURLRequest *request = [NSURLRequest];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

// find Documents directory and append your local filename
NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
documentsURL = [documentsURL URLByAppendingPathComponent:@"localFile.pdf"];

// and finally save the file
[data writeToURL:documentsURL atomically:YES];

Note that this method will download the file on the main thread and hence block anything else until it’s finished. Probably not so good for larger downloads. Instead, you can kick it off on another thread using sendAsynchronousRequest:queue:completionHandler.

In your simulator you can check that the file has downloaded, or you can list the Documents directory like so:

// list contents of Documents Directory just to check
NSURL *documentsURL = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

NSArray *contents = [[NSFileManager defaultManager]contentsOfDirectoryAtURL:documentsURL includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];

NSLog(@"%@", [contents description]);

If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.