azamsharp
azamsharp

Reputation: 20066

NSFileManager contentsOfDirectoryPath returning empty

I have an images group inside my xCode project. I am trying to get all the files from inside that folder into my app.

 NSFileManager *fm = [NSFileManager defaultManager];
    NSArray *dirContents = [fm contentsOfDirectoryAtPath:@"/Images/" error:nil];

The above code always returns an empty array. I added the group in xCode 4.2 by right click and then "New Group".

Upvotes: 0

Views: 726

Answers (1)

Joris Kluivers
Joris Kluivers

Reputation: 12081

The path you are using is probably not the correct one. /Images/ will refer to images in the root of your sandbox. If the images in your folder are added as a resource in your project, they will be stored in the Resources directory in your app, probably not even in the Images directory.

You also want to read the error to see what's wrong. That's what it is for:

NSErorr *error = nil;
NSArray *dirContents = [fm contentsOfDirectoryAtPath:@"/Images/" error:&error];
if (!dirContents) {
    // inspect error
} 

Use -[NSBundle resourcePath] to get a path to your applications resources directory.

Understand that your project structure is not equal to the location your resources will end up in your application. Resources are all copied to the Resources directory using your targets Copy Bundle Resources buid phase.

If you really want to add certain files in a different directory in your resources directory add a new Copy Files phase, with a destination of Resources and a Subpath named with your folder, like Images

Then you can loop over those images using your file manager and the path you get using:

[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Images"];

Upvotes: 2

Related Questions