Search code examples
iossandbox

Accessing and using the files in the app sandbox


I have an iOS application in which I download some files from a remote server and store them in the app sandbox directory, Documents. I am sure the files are saved in the sandbox properly because when I run the following piece of code:

NSFileManager* fileManager = [NSFileManager defaultManager];
NSString* documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSError* error;
NSLog(@"%@",[fileManager contentsOfDirectoryAtPath:documentPath error:&error]);

I get the following output:

2014-07-09 17:39:07.768 Sample[13413:60b] (
    "test.json",
    "test.png"
)

However, I can not access these files in the Documents directory. I try to get the contents of test.json with the following code:

NSString* testJsonDir = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"json"];
NSString* testJson = [NSString stringWithContentsOfFile:testJsonDir encoding:NSUTF8StringEncoding error:&error];

This returns testJsonDir as nil and gives an error with code 258. Is there some other way to do this?


Solution

  • [NSBundle mainBundle] refers to the .app bundle, not the Documents directory. To access test.json, use this:

    NSError *error = nil;
    NSURL *documentsUrl = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask][0];
    NSString *testJson = [NSString stringWithContentsOfURL:[documentsUrl URLByAppendingPathComponent:@"test.json"] encoding:NSUTF8StringEncoding error:&error];
    

    I'm using -URLsForDirectory:inDomains: instead of NSSearchPathForDirectoriesInDomains() because former is a preferred way.