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:

NSArray *contents = [[NSArray alloc]init];
contents =[[NSFileManager defaultManager]contentsOfDirectoryAtURL:yourURL includingPropertiesForKeys:nil options:nil error:nil];
NSLog(@"%@", contents);

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.

One thought on “How to list the contents of an NSURL

  1. FYI, you are leaking an array. There’s no need to allocate an array in the first line. The contentsOfDirectory returns an autoreleased array. If you want to retain that, call retain on the contents after it is returned from contentsOfDirectory

Leave a Reply

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