Tag Archives: NSFileManager

How to test the existence of a file with NSFileManager

Here’s how you can check if a file exists in your app’s Documents directory:

This example relies on another method which is usually part of the AppDelegate.m file called applicationDocumentsDirectory. It will return an NSURL to your Documents directory. Just in case you’re working on a project which does not include it, here it is:

How to list the contents of an NSURL

On the iOS simulator we have the luxury of peeking inside our virtual devices with the Finder. We can do this by heading over to the Finder, holding down Option and clicking Go. This will bring up the Library, in which you can navigate to Application Support / iPhone Simulator / 7.0 / Applications / followed by a weird string. One of those will contain your app and all its directories.

But on a real device we’re not so lucky. Has a file really been copied the way we intended it to? NSFileManager to the rescue! Here’s how to read out the contents of a directory at an NSURL:

contentsOfDirectoryAtURL returns an NSArray (of NSURLs) which you can loop through and display any way you like. If you have a file path instead, you can use contentsOfDirectoryAtPath instead.

How to copy a file from the Main Bundle into the Documents Directory in iOS

You can do this either by using paths or NSURLs. Apple recommends using NSURLs, so here’s how it works.

In this example we’re copying a file called “Amy.png” which exists in the app’s main bundle.

How to delete a file

Once you have a reference to the file in question you can call the removeItemAtPath method:

This does not work with wildcards in the file name (for example *.jpg).

How to test if a file exists

Imagine we had a file that we’ve saved:

Before accessing it we can determine if it exists or not:

How to load a UIImage that we’ve previously saved