Tag Archives: NSData

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 test the size of a UIImage (in bytes)

We can use NSData’s length method for this. Imagine your UIImage is yourImage:

[imageData length] returns a double in bytes, which will be the size of your image.

This is useful if you’d like to save something and you’re limited in size, such as iCloud Key Value storage where a data object may only be 1MB in size or smaller.