Reputation: 2280
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?
Upvotes: 1
Views: 696
Reputation: 2511
[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.
Upvotes: 1
Reputation: 122458
[NSBundle pathForResource:ofType:]
will locate files within the app bundle, not the documents folder.
You want:
NSString *testJsonDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *testJsonFile = [testJsonDir stringByAppendingPathComponent:@"test.json"];
NSString *testJson = [NSString stringWithContentsOfFile:testJsonFile
encoding:NSUTF8StringEncoding
error:&error];
Upvotes: 1