Josh Brown
Josh Brown

Reputation: 53063

NSSearchPathForDirectoriesInDomains returns the wrong directory

I'm using NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) to get the application documents directory in my app, but the array that's returned contains only one object, and it's an unwritable, incorrect directory:

/Users/me/Library/Application Support/iPhone Simulator/Documents

I found this question which indicates that the problem is related to provisioning, but the answer says little more than that. So I guess I'm asking a duplicate question, but the answer to that question is insufficient, so I'm hoping to get an actual answer in this one.

Upvotes: 12

Views: 12834

Answers (4)

Axy
Axy

Reputation: 384

I'm having the exact same issue, and in my case it's because I'm running the code from an XCTest class.

My guess is that the tests are not run in the application sandbox.

That's because my tests are related to a static library project, included in the main project.

As soon as I run the exact same code from a run of my app, the paths are returned correctly.

Hope this helps.

Upvotes: 0

Rob
Rob

Reputation: 4434

Hmm ... so one reason that the directory returned might be different that what you'd expect for an app could be related to the Xcode target type. This wouldn't happen to be a testing target would it? in which case the correct answer could well be an answer w/o an application GUID in it, since in fact it's not an application. This google group discussion implies that if this is the case, you'd be good with simply creating the directory.

Just for grins, I created the directory /Users/me/Library/Application Support/iPhone Simulator/Documents from the terminal window, and now it appears to run. There are still test errors, but those might be real.

I'd recommend that you change your test app to create the documents directory if it's missing - something like:

  if(![[NSFileManager defaultManager] createDirectoryAtPath:NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) withIntermediateDirectories:YES attributes:nil error:NULL])
        NSLog(@"Error: Create folder failed %@", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES));

Upvotes: 8

Oscar Gomez
Oscar Gomez

Reputation: 18488

You can try this:

 /**
 Returns the path to the application's Documents directory.
 */
- (NSString *)applicationDocumentsDirectory {
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}

I believe you are only missing the lastObject message.

Upvotes: 1

vocaro
vocaro

Reputation: 2779

This works for me:

[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory
                                        inDomains:NSUserDomainMask] lastObject];

Upvotes: 3

Related Questions