Tag Archives: NSURLRequest

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

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:

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:

How to load a URL into a UIWebView

The UIWebView as a method called loadRequest which takes an NSURLRequest as a parameter. This in turn can be created from an NSURL.

Here’s how this works: